patchValue 方法和 setValue 方法只能改变表单的值,但是无法改变表单的验证规则,有时我们根据不同情况执行不同的校验规则,则用该方法
this.validateForm.get('key').setValidators(Validators.required);
示例如下:
.html
<form nz-form [formGroup]="validateForm" class="basicInfoCreateContent" (ngSubmit)="submitForm($event,validateForm.value)">
<nz-form-item>
<nz-form-control [nzSpan]="24">
<input nz-input formControlName="name" maxlength="20" placeholder="请输入" (blur)="onBlur()">
<nz-form-explain *ngIf="validateForm.get('name').dirty && validateForm.get('name').errors || validateForm.get('name').pending ">
<ng-container *ngIf="validateForm.get('name').hasError('required')">
名称不能为空!
</ng-container>
<ng-container *ngIf="validateForm.get('name').hasError('duplicated')">
用户名已存在!
</ng-container>
</nz-form-explain>
</nz-form-control>
</nz-form-item>
</form>
.ts
export class BranchEdit {
constructor(private message: NzMessageService, private fb: FormBuilder) {
this.validateForm = this.fb.group({
name: ['', [ Validators.required ]], // 名称
});
console.log(this)
};
validateForm: FormGroup;
onBlur(){
this.validateForm.get('name').setErrors({ error: true, duplicated: true });
}
}
网友评论