【发布时间】:2018-01-10 02:24:17
【问题描述】:
我是 Angular 2 的新手。当我有条件地验证一个字段时,我遇到了一个问题。我有一个选择框,并且其他选项很少。当有人更改为其他选项时,将打开一个文本框并且这是一个必填字段。如果有人没有写任何东西,则在触摸另一个文本框后,它会引发验证错误。这工作正常。但是如果我更改为其他选项,则在收到错误后需要对其他文本进行验证盒子仍然存在。这就是为什么无法提交表单的原因。
HTML
<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>
TS
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();
}
除其他之外,所有验证工作正常。 当我更改为其他时,它给了我错误“无法读取 null 的属性 'setValidators'”。实际上我正在寻找的是,当有人选择其他人时,输入文本将需要验证器。否则没有验证器。
【问题讨论】:
标签: angular