Angular Material 将复选框的选中状态作为表单组中其他控件的只读基础

Angular Material use the checked status of checkbox as a readonly basis of other control in form group

我是 angular 的新手,我想使用复选框的选中状态作为文本区域只读 属性 的基础。

<div fxlayout="row" fxLayoutAlign="center center" *ngFor="let test of cosmetriTests.controls; let i=index" [formGroupName]="i">
 <mat-form-field class="w-25-p" appearance="outline" >
      <textarea [id]="'actualCoaField_'+i"
          matInput
          formControlName="actual_coa_qualifier"
          (keyup) = "evaluateCoa()"
          [readonly] = "test.checked.include==false"
          required>
      </textarea>
 </mat-form-field>

 <mat-checkbox
     formControlname="include"
     [checked]="true"
     [required]="true"
 </mat-checkbox>
</div>

提前谢谢大家。

没有 material 方便,我只是尝试直接使用 angular,并且成功了:

        <textarea [id]="'actualCoaField_'+i"
             matInput
             [disabled]="!myCheckbox.checked"
         >
         </textarea>

         <input type="checkbox"
             #myCheckbox
             (change)="true"
         />

有两点需要注意:

1) #myCheckbox 不需要附加循环索引,因为模板名称在它们的范围内是本地的(并且 *ngFor 在每次迭代时创建一个新的 ng 模板),并且

2)看似不必要的(change)=true实际上是必要的,因为它说服Angular执行屏幕更新。

您可以使用 ngModel 进行 2 种数据绑定。

 <mat-form-field class="w-25-p" appearance="outline" >
          <textarea [id]="actualCoaField"
              matInput
              (keyup) = "evaluateCoa()"
              [readonly] = "!isCheckboxChecked"
              required>
          </textarea>
     </mat-form-field>

    <mat-checkbox [(ngModel)]="isCheckboxChecked"
         (change)="checked()"
         [required]="true">
     </mat-checkbox>

现在基于复选框状态的文本区域将是 enabled/disabled。

创建了一个 stackblitz https://stackblitz.com/edit/angular-8fuu3p?file=app/checkbox-overview-example.html

将代码更改为 [readonly] = "test.include.value==false" 并检查它是否有效

<div fxlayout="row" fxLayoutAlign="center center" *ngFor="let test of cosmetriTests.controls; let i=index" [formGroupName]="i">
 <mat-form-field class="w-25-p" appearance="outline" >
      <textarea [id]="'actualCoaField_'+i"
          matInput
          formControlName="actual_coa_qualifier"
          (keyup) = "evaluateCoa()"
          [readonly] = "test.checked.include==false"
          required>
      </textarea>
 </mat-form-field>

 <mat-checkbox
     formControlname="include"
     [checked]="true"
     [required]="true"
 </mat-checkbox>
</div>

您可以在复选框值更改时添加事件发射器函数,

我的 ts 代码:

readOnlyTextArea = true;
textAreaReadonly( value ) {
  this.readOnlyTextArea = !this.readOnlyTextArea;
}

我的Html代码:

<mat-form-field class="example-full-width">
      <textarea [readonly] = "readOnlyTextArea" matInput placeholder="Leave a 
      comment"></textarea>

</mat-form-field>
<mat-checkbox color="primary" formControlname="include" [checked]="true" 
       (change)="textAreaReadonly($event)" [required]="true">Checkbox
</mat-checkbox>