はじめに
Angularを使用していて、バリデーションをするときに手こずったので、自分用と同じ問題で困っている人のために実装方法を記録しておきたいと思います。
実装例
<form #loginForm="ngForm" novalidate>
<label for="mail-address">メールアドレス</label>
<input id="mail-address" type="email" name="mail"
[(ngModel)]="login.mail" #mail="ngModel" required email/>
<div *ngIf="mail.errors && (mail.dirty || mail.touched)"
class="alert alert-danger">
<div [hidden]="!mail.errors.required">
入力してください
</div>
</div>
</form>
import { Component, OnInit } from '@angular/core';
@Component({
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
login = {
mail: '',
password: ''
};
constructor() {}
ngOnInit() {
}
}
注意点
以下処理を入れないと、ページ表示時にもバリデーションが働いてしまうので注意する必要がある。
*ngIf="mail.errors && (mail.dirty || mail.touched)"
参考