我是角色2的新手。当我有条件地验证一个字段时,我遇到了一个问题。我有一个选择框,并且有很少的选项和其他。当一个更改为其他时,文本框将打开,它是一个必填字段。触摸另一个文本框后,如果任何人没有写任何东西,那么它抛出一个验证错误。这是正常工作。但是如果我改变到其他选项获得其他文本所需的验证后获得错误盒子仍然存在。这就是为什么无法提交表单的原因。
<label for="sel1">Author Name:</label>
<select (change)="changeExistingAuthorIdName()" placeholder="Select Author" class="form-control" id="authorNameNewList" formControlName="authorNameNewList">
<option *ngFor="let authorIdNameEach of authorIdName" [ngValue]="authorIdNameEach">{{authorIdNameEach.authorname}}</option>
<option [ngValue]="otherAuthorList">Other</option>
</select>
<mat-error *ngIf="newBookForm.controls.authorNameNewList.touched && newBookForm.controls.authorNameNewList.hasError('required')"> Please Select Author
</mat-error>
<div class="row" *ngIf="otherAuthorInput">
<div class="col-sm-12">
<label for="sel1">Enter Author Name:</label>
<input type="text" formControlName="authorNameNew" class="form-
control" id="authorNameNew">
<mat-error *ngIf="newBookForm.controls.authorNameNew.touched && newBookForm.controls.authorNameNew.hasError('required')"> Please Enter Author Name
</mat-error>
</div>
</div>
constructor(private _DashboardService: DashboardService, private fv: FormBuilder) {
this.fb = fv;
}
ngOnInit() {
this.newBookForm = this.fb.group({
bookNameNew: ['', Validators.compose([Validators.required])],
authorNameNewList: ['', Validators.compose([Validators.required])],
categoryNew: ['', Validators.compose([Validators.required])]
})
}
otherAuthorInput = false;
otherAuthorList = {
id: 99,
authorname: 99
};
changeExistingAuthorIdName() {
if (this.newBookForm.value.authorNameNewList.id == 99) {
this.otherAuthorInput = true;
// this.newBookForm.get('authorNameNew').setValidators([Validators.required]);
this.newBookForm.get('authorNameNew').setValidators([Validators.required]);
} else {
this.otherAuthorInput = false;
this.newBookForm.get('authorNameNew').clearValidators();
}
this.newBookForm.get('authorNameNew').updateValueAndValidity();
}
所有验证工作正常,除了其他。 它给了我错误&#34;无法读取属性&#39; setValidators&#39; of null&#34;当我换到其他人的时候。实际上我正在寻找的是,当某人选择其他时,输入文本将具有所需的验证器。否则没有验证者。
答案 0 :(得分:0)
需要在FormGroup中将authorNameNew声明为FormControl
this.newBookForm = this.fb.group({
bookNameNew: ['', Validators.compose([Validators.required])],
authorNameNewList: ['', Validators.compose([Validators.required])],
categoryNew: ['', Validators.compose([Validators.required])],
authorNameNew: ['', Validators.compose([Validators.required])]
})
如果您的FormControl不是必需的,请不要在示例中添加Validators.required ..:authorNameNew
this.newBookForm = this.fb.group({
bookNameNew: ['', Validators.compose([Validators.required])],
authorNameNewList: ['', Validators.compose([Validators.required])],
categoryNew: ['', Validators.compose([Validators.required])],
authorNameNew: ['']
})