Angular16 已禁用,无法使用reactiveForms

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

我正在使用 Angular 16 制作一个反应式表单。当选中该复选框时,我想阻止数据输入到其中一个输入,即禁用它。我的代码如下,但是不起作用,你能帮我吗?当我删除 formcontrolname 时,它会被禁用,但随后我无法接收输入的数据。

 <form [formGroup]="personelForm">
                  <div class="row">
                    <mat-checkbox class="example-margin" formControlName="isCheck">Not Phone</mat-checkbox> <br>
                  </div>

                  <div class="row">

                    <mat-form-field style="margin-right: 10px;">
                      <mat-label>Phone</mat-label>
                      <input matInput type="number" formControlName="phone" 
                        [disabled]="personelForm.get('isCheck').value">
                    </mat-form-field>


                    <mat-form-field style=" margin-right: 10px;">
                      <mat-label>Name</mat-label>
                      <input matInput type="text" formControlName="name">
                    </mat-form-field>

                    <mat-form-field style="margin-right: 10px;">
                      <mat-label>Surname</mat-label>
                      <input matInput type="text" formControlName="surname" >
                    </mat-form-field>

                    
                  </div>

                </form>

**

personelForm: FormGroup;
constructor(private fb: FormBuilder){}
  reloadForm() {
    this.personelForm = this.fb.group({
      isCheck:  new FormControl(false),
      phone: new FormControl(0),
      name:  new FormControl(''),
      surname:  new FormControl('')

    });
    
    }
    

  ngOnInit() {
    this.reloadForm();
    

  

}

angular angular-material angular-reactive-forms
2个回答
0
投票

使用

[attr.disabled]
属性绑定)而不是
[disabled]

 <input
  matInput
  type="number"
  formControlName="phone"
  [attr.disabled]="personelForm.get('isCheck')!.value"
/>

或者,您可以订阅

isCheck
控件的
valueChanges
可观察对象并启用/禁用组件中的
phone
控件。

this.personelForm.get('isCheck')!.valueChanges.subscribe((isCheck) => {
  if (isCheck) this.personelForm.get('phone')!.disable();
  else this.personelForm.get('phone')!.enable();
});

演示@StackBliz


0
投票

我建议使用 Yong Shun 的替代解决方案,但直接访问控件属性以避免不必要的非空断言:

this.personelForm.controls['isCheck'].valueChanges.subscribe((isCheck) => {
  if (isCheck) this.personelForm.controls['phone'].disable();
  else this.personelForm.controls['phone'].enable();
});
© www.soinside.com 2019 - 2024. All rights reserved.