Angular Reactive 表单 - 禁用属性

问题描述 投票:0回答:1

我有一些

disabled
字段的 HTML 代码,这些字段具有将
check-box
标记为
dissabled
的不同条件:

<!-- RECIPIENTS -->
<div class="row mb-4 mt-2">
    <div class="col-12" formArrayName="recipients">
        <label class="mb-2">{{ departmentsOfSystem.includes(role.toLowerCase()) ? 'Sistemas destinatarios:' : 'Equipos destinatarios:' }}</label>

        <div class="d-flex justify-content-start flex-wrap">
            <mat-checkbox
                *ngFor="let recipient of getRecipientsByRoleAndTeam(role)"
                class="mr-3"
                [name]="recipient?.id"
                [checked]="recipient.checked"
                [disabled]="(recipient.id === 'GCRG' && !isCdGSelected()) || getDisabledRecipient(recipient)"
                (change)="onChangeRecipientState($event)"
            >
                {{ recipient.description }}
            </mat-checkbox>
        </div>
        
        <div *ngIf="role.toLowerCase() == 'cdg'">
            <label class="mb-2 mt-2">Autovalidación: </label>
        
            <div class="d-flex justify-content-start flex-wrap">
                <mat-checkbox
                    *ngFor="let recipient of getRecipientsByRoleAndTeam(role, 'VALIDACION')"
                    class="mr-3"
                    [name]="recipient?.id"
                    [checked]="recipient.checked"
                    [disabled]="!isCdGRole() || !isCdGSelected() || getDisabledRecipient(recipient)"
                    (change)="onChangeRecipientState($event)"
                >
                    {{ recipient.description }}
                </mat-checkbox>
            </div>
        </div>                          
    </div>
</div>

代码运行完美,但我一直收到控制台消息:

 It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
      when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
      you. We recommend using this approach to avoid 'changed after checked' errors.
       
      Example: 
      form = new FormGroup({
        first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
        last: new FormControl('Drew', Validators.required)
      });

我尝试了

[attr.disabled]
,但消息不断出现,或者在某些时候组件停止工作。

如何处理此错误并使我的代码保留同一 FormArray 的禁用属性?

angular disabled-control
1个回答
0
投票

对于新标准,您需要从组件代码中启用/禁用反应式表单元素。 示例:

this.myReactiveForm.get('name')?.disable();

因此,您需要将更改捕获到函数中,并且该函数应该启用/禁用反应形式的特定元素。

粗略的例子:

changeHappen(): void {
  if (needToDisable) {
    this.myForm.get("elementToDisable")?.disable();
  } else {
    this.myForm.get("elementToDisable")?.enable();
  }
}

额外参考: https://v17.angular.io/api/forms/FormControl

© www.soinside.com 2019 - 2024. All rights reserved.