Angular 5 - 有条件的必需文本区域

标签 angular textarea required

如果单击复选框,则会出现文本区域并且是必需的[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" 则效果很好。 我猜想 ma​​t-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/

相关文章:

angular - VS code/Angular - Linter 无法识别通过共享模块导入的组件

angular - 为什么我没有执行任何数据更改时会收到 NG0901 错误?

html - 在文本区域中显示换行符之间的分隔

python - 最好的 python 库,当用户提交时,使 textarea 在网页中安全

javascript - 返回语句在 Ajax 和 Angular 中不起作用

javascript - Protractor 卡在元素单击上

javascript - TextArea 返回错误值

javascript - 仅在元素显示时才需要必填字段

JavaScript 如果复选框被选中则不起作用

html - 一起使用 required 和 readonly 属性