文章内容

2020/7/23 10:52:47,作 者: 黄兵

Angular FormGroup和FormControl示例

处理表单是一件非常麻烦的事,主要体现在以下几个方面:

1、单个表单需要检查输入;

2、同时需要验证(电话号码,邮件,字符等),并给出提示;

3、在最后提交时,需要检查所有表单是否填写有问题。

综合上面一些问题,这里有一个Angular表单,做一些总结:

<form [formGroup]="noticeFormGroup">
<mat-form-field appearance="outline">
<mat-label>Notice title</mat-label>
<input matInput [formControl]="titleFormControl" placeholder="Please enter notice title">
<mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
<mat-error *ngIf="titleFormControl.invalid"><mat-icon>info</mat-icon>{{getErrorMessage()}}</mat-error>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Notice keywords</mat-label>
<input matInput [formControl]="keywordsFormControl" placeholder="Please enter notice keywords">
<mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
<mat-error *ngIf="keywordsFormControl.invalid"><mat-icon>info</mat-icon>{{getErrorMessage()}}</mat-error>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Notice description</mat-label>
<input matInput [formControl]="descriptionFormControl"
placeholder="Please enter notice description">
<mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Notice</mat-label>
<textarea matInput [formControl]="noticeFormControl" placeholder="Please enter notice" rows="10"
[(ngModel)]="markdown"></textarea>
<mat-error *ngIf="noticeFormControl.invalid"><mat-icon>info</mat-icon>{{getErrorMessage()}}</mat-error>
</mat-form-field>
<markdown [data]="markdown"></markdown>
<div class="submit-button">
<button mat-raised-button color="primary" (click)="submit($event)"
[disabled]="noticeFormGroup.invalid">Primary
</button>
</div>
</form>

这里有FormControl和FormGroup,验证代码:

export class EditorComponent implements OnInit {
errorMessages: string[] = [];
markdown = '# Markdown';
noticeFormGroup: FormGroup;
titleFormControl = new FormControl('', [Validators.required]);
keywordsFormControl = new FormControl('', [Validators.required]);
descriptionFormControl = new FormControl('');
noticeFormControl = new FormControl('', [Validators.required]);

selectedIndex = 0;

constructor(fb: FormBuilder) {
this.noticeFormGroup = fb.group({
titleForm: this.titleFormControl,
keywords: this.keywordsFormControl,
description: this.descriptionFormControl,
notice: this.noticeFormControl
});
}

ngOnInit(): void {

}

getErrorMessage() {
if (this.titleFormControl.hasError('required') || this.keywordsFormControl.hasError('required') || this.noticeFormControl.hasError('required')) {
return 'You must enter a value';
}
}

submit(e) {

}
}

这里将FormControl变换成FormGroup,分组之后,方便按钮的一个状态。按钮只需要验证FormGroup的状态,只要有一个没有验证通过,按钮即为不可用状态,防止错误提交。

同时getErrorMessage()给出了没有验证通过的提示。


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Angular FormGroup和FormControl示例

分享到:

发表评论

评论列表