LoginSignup
0
0

Angular:Formの入力チェック

Posted at

前書き

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

Formの入力チェック

  • HTMLテンプレートを作成
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>

ポイント:
<form #loginForm="ngForm" (ngSubmit)="onLogin()">
<input [(ngModel)]="user.Mail" required minlength="2" maxlength="100" #Mail="ngModel">
<span [hidden]="!Mail.errors?.required">メールアドレスは必要です。</span>
<button mat-stroked-button [disabled]="loginForm.invalid" color="primary" (click)="onLogin()">ログイン</button>

  • HTMLテンプレートを作成
ts
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 () {
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0