如果单击复选框,则会出现文本区域并且是必需的[required]="otherVendorsChecked == true ? true : false" 如果我选择复选框而不是取消选择它,则仍然需要文本区域输入。 有谁知道我做错了什么?
<div>
<mat-checkbox [ngModelOptions]="{standalone: true}" [(ngModel)]="otherVendorsChecked">Other option:</mat-checkbox>
</div>
<mat-form-field *ngIf="otherVendorsChecked == true">
<textarea matInput formControlName="otherVendors" [required]="otherVendorsChecked == true ? true : false"></textarea>
</mat-form-field>
[编辑]
如果我删除 *ngIf="otherVendorsChecked == true" 则效果很好。 我猜想 mat-form-field 仅在 ngIf 条件下被删除,因此对所需的属性没有更多影响。
这是我在 ngOnInit 中的表单:
this.form = new FormGroup({
otherVendors: new FormControl('', [Validators.minLength(2)]),
...
});
this.fillForm();
在我的 fillForm 中我有以下代码:
this.form.controls['otherVendors'].setValue(this.lastFacilityDetailOfCalendarEvent.otherVendors);
if(this.lastFacilityDetailOfCalendarEvent.otherVendors != null && this.lastFacilityDetailOfCalendarEvent.otherVendors.length > 0) {
this.otherVendorsChecked = true;
}
最佳答案
[已编辑]
最后,经过一点实验,我发现这都是因为 <mat-form-field *ngIf="otherVendorsChecked == true">
.
每次改变otherVendorsChecked
值时,FormControl 将在必需和不需要之间切换。当 otherVendorsChecked
时为 true 时,您的 FormControl 将更改为必需的,但是当 otherVendorsChecked
时更改为 false,甚至在将 FormControl 更新为不需要之前 *ngIf
会在触发 FormControl 的更改事件之前从 DOM 中删除 textarea 元素,因此现在 FormControl 不知道将其设为不需要。
为了快速修复,不要使用 *ngIf
您可以从 View 中隐藏该部分/元素,也许使用 display: none;
或类似的东西。
希望这有帮助。
关于Angular 5 - 有条件的必需文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289944/