mat-select中的动态禁用/启用无法正常工作

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

我正在创建一个带有mat-select的反应形式。

<mat-form-field>
    <mat-select placeholder="Salutation*" formControlName="salutation">
      <mat-option *ngFor="let salutation of salutations" [value]="salutation.id">
        {{ salutation.label }}
      </mat-option>
    </mat-select>
</mat-form-field>

形成:

this.form = this.fb.group({
  person: this.fb.group({
    salutation: ['', Validators.required],
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    email: ['', Validators.required]
  })     
});

我需要根据其他输入值禁用/启用此选择。由于反应形式不再支持[禁用],因此我使用了以下内容

this.form.get('person').get('salutation').disable();

问题是当我尝试启用选择返回时

this.form.get('person').get('salutation').enable();

它只是不起作用。有什么想法吗?

PS:使用disabled属性工作正常,但它会发出警告

看起来您正在使用带有响应式表单指令的disabled属性。如果在组件类中设置此控件时将disabled设置为true,则实际将在DOM中为您设置disabled属性。我们建议使用此方法来避免“检查后更改”错误。

  Example: 
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

谢谢!

angular material-design angular-material2
2个回答
0
投票

我没有看到你从哪里获得你的地址。除了查看以下作品的地址。

  • 要么你没有共享你的整个代码,要么只是: 。this.form.get( '人')得到( '称呼')使能()。

  • 你错过了一个支架,或者有一个支架

email: ['', [Validators.required]]
  • 您在表单组中有一个人员组,因此您可能需要定义formGroupName div,或者您没有共享整个代码。

<form [formGroup]="form">
  <div formGroupName="person">
    <mat-form-field>
      <mat-select placeholder="Salutation*" formControlName="salutation">
        <mat-option *ngFor="let salutation of salutations" [value]="salutation.id">
          {{ salutation.label }}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </div>
</form>
  • [disabled]仍然只能输出一个警告,但是你通过在同一个json对象中添加它作为第二个参数来实现组件中的禁用控制

  ngOnInit() {
    this.form = this.fb.group({
      person: this.fb.group({
        salutation: [{value: '', disabled: true}],
        firstName: ['', Validators.required],
        lastName: ['', Validators.required],
        email: ['', [Validators.required]]
      })
    });


    this.form.get('person').get('salutation').enable();
  }

0
投票

当我尝试重新初始化窗体并将控件设置为启用时,我遇到了这个问题。 (场景显示的细节记录只能由该记录的所有者编辑)。除了select控件之外,这适用于大多数控件。我设法通过使用适合您的代码的以下解决方案:

this.form.controls["salutation"].enable();
© www.soinside.com 2019 - 2024. All rights reserved.