angular: Custom form input verification in dynamic responsive forms and prompts for corresponding information
Part of the code is as follows:
ts:
this.detailForm = this.fb.group({
dataSourceParamName: [null, [Validators.required, Validators.maxLength(40)] ], //minLength maxLength
description: [null, Validators.maxLength(200) ],
dutyDepartmentParamList: [null, [Validators.required]],
relatedTaskFlag: [true];
});
get dataSourceParamName() {
return this.detailForm.get('dataSourceParamName')}
get description() {
return this.detailForm.get('description') }
html:
<nz-form-item *ngIf="detailItem.dataSourceType === 'THIRD'">
<nz-form-label [nzSpan]="8" nzFor="dataSourceParamName" nzRequired>{
{
'节点字段名称'}}</nz-form-label>
<nz-form-control [nzSpan]="14" nzErrorTip="{
{dataSourceParamNameErrors}}">
<input nz-input id="dataSourceParamName" formControlName="dataSourceParamName"
[(ngModel)]="detailItem.dataSourceParamName">
<div *ngIf="dataSourceParamName.invalid && (dataSourceParamName.dirty || dataSourceParamName.touched)"
class="alert alert-danger">
<div *ngIf="dataSourceParamName.errors?.['required']">
Field Required
</div>
<div *ngIf="dataSourceParamName.errors?.['maxlength']">
请输入节点字段名称40字符以内
</div>
</div>
</nz-form-control>
</nz-form-item>
ps:
Dynamically adding controls may cause validation to fail. The form verification has been performed before adding the control, but after the control is added, the form verification is not re-executed.
To solve this problem, you can manually adjust the form validation using the updateValueAndValidity() method to ensure the validity of the validator. After adding or removing a control, you can call this method in the corresponding branch, for example:
if (data === 'THIRD') {
this.detailForm.addControl('dataSourceParamName', this.fb.control(null, Validators.maxLength(40)));
this.detailForm.get('dataSourceParamName').updateValueAndValidity();
} else {
this.detailForm.removeControl('dataSourceParamName');
}
Custom validation reference official website: https://angular.cn/guide/form-validation#adding-custom-validators-to-reactive-forms