(モジュールの読み込み)
app/form/form.page.ts
// add
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
(エラーメッセージの定義)
app/form/form.page.ts
validations = {
'username': [
{ type: 'required', message: 'お名前は入力必須です' },
],
'email': [
{ type: 'required', message: 'メールアドレスは入力必須です' },
],
'content': [
{ type: 'required', message: 'お問い合わせ内容は入力必須です' },
],
};
(バリデーションフォームの定義)
app/form/form.page.ts
public loginForm: FormGroup;
constructor(
public router: Router,
public formBuilder: FormBuilder) {
this.loginForm = new FormGroup({
username: new FormControl('', Validators.compose([
Validators.required
])),
email: new FormControl('', Validators.compose([
Validators.required
])),
content: new FormControl('', Validators.compose([
Validators.required
])),
});
}
(お名前フォームのみ)複数入力フォームがある場合は適宜追加すること
<form [formGroup]="loginForm">
<ion-item>
<ion-label position="stacked">お名前 <ion-text color="danger">*</ion-text></ion-label>
<ion-input type="text" formControlName="username"></ion-input>
<!-- error message -->
<div class="error-container">
<ng-container *ngFor="let validation of validations.username">
<div class="error-message"
*ngIf="loginForm.get('username').hasError(validation.type) && (loginForm.get('username').dirty || loginForm.get('username').touched)">
<ion-icon name="information-circle-outline" color="danger"></ion-icon>
<ion-text color="danger">{{ validation.message }}</ion-text>
</div>
</ng-container>
</div>
<!-- /error message -->
</ion-item>
<div class="ion-padding">
<ion-button [disabled]="!loginForm.valid" (click)="onClickSubmit()" expand="block" type="submit"
class="ion-no-margin">送信する</ion-button>
</div>
</form>