我在用着matInput
and mat-form-field
(@angular/material) 在 Angular 组件中,我无法禁用matInput
.
可以在这里看到一个工作示例。 https://stackblitz.com/edit/angular-7ceq7v
我似乎错过了一些明显的东西,但我一生都无法弄清楚是什么。这是一个错误吗?
如果我删除[formControlName]
来自CustomFormInputComponent
,然后我可以成功禁用matInput
CustomFormInputComponent
:
import { Input, Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-custom-form-input',
template: `
<mat-form-field [formGroup]="form">
<input matInput placeholder='Name' [formControlName]="formControlName" [disabled]='disabled'>
</mat-form-field>
`,
})
export class CustomFormInputComponent {
@Input() form: FormGroup;
@Input() formControlName: string = 'name';
@Input() disabled = false;
}
AppComponent
:
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<p>At least one of these inputs should be disabled, but none are :(</p>
<app-custom-form-input [form]="form" [disabled]='true'></app-custom-form-input>
<app-custom-form-input [form]="form" [disabled]="'disabled'"></app-custom-form-input>
`,
})
export class AppComponent {
public form: any;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
name: ''
})
}
}
任何见解都将不胜感激!
Answer
有关 David 答案的更多背景信息:Angular 根据反应式表单控件的禁用状态更新 DOM 状态。我认为正在发生的事情:角度正在渲染CustomFormInputComponent
之前AppComponent
并将组件呈现为禁用状态。然后AppComponent被渲染并且form
是用name
控制启用。然后 Angular 取消禁用 DOM 输入元素(这是设计的行为)。