Angular: 表单输入验证

序言

    自分の勉強メモ、ご参考まで

表单的输入检查

    HTMLテンプレートを作成
<form #loginForm="ngForm" (ngSubmit)="onLogin()">
  <mat-form-field style="width:300px;">
    <mat-label>Mail Address</mat-label>
    <input matInput id="Mail" name="Account" type="email" [(ngModel)]="user.Mail" required minlength="2" maxlength="100" #Mail="ngModel" style="ime-mode: inactive">
    <button *ngIf="user.Mail" matSuffix mat-icon-button aria-label="Clear" (click)="user.Mail=''"><mat-icon>close</mat-icon></button>
    <mat-hint>
      <span [hidden]="!Mail.errors?.required">メールアドレスは必要です</span>
      <span [hidden]="!Mail.errors?.minlength">2文字以上入力ください</span>
      <span [hidden]="!Mail.errors?.maxlength">100文字以下入力ください</span>
    </mat-hint>
  </mat-form-field>
  <button mat-stroked-button [disabled]="loginForm.invalid" color="primary" (click)="onLogin()">ログイン</button>
</form>

要点:



    HTMLテンプレートを作成
import {Component} from '@angular/core';
import {MatIconModule} from '@angular/material/icon';
import {MatButtonModule} from '@angular/material/button';
import {MatInputModule} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';
import {FormsModule} from '@angular/forms';
import {NgIf} from '@angular/common';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  standalone: true,
  imports: [
    MatIconModule, 
    MatButtonModule, 
    MatInputModule, 
    MatFormFieldModule, 
    FormsModule, 
    NgIf, 
  ], 
})

export class LoginComponent {
  user = {
    Mail: '',
    Password: '',
  };

  async onLogin () {
  }
}
广告
将在 10 秒后关闭
bannerAds