我在 Angular 组件中使用 matInput
和 mat-form-field
(@angular/material),我无法禁用 matInput
。
A working example can be seen here.
似乎我遗漏了一些明显的东西,但对于我的生活我无法弄清楚是什么。这是错误吗?
如果我从 CustomFormInputComponent
中删除 [formControlName]
,那么我可以成功禁用 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;
}
应用组件
:
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: ''
})
}
}
非常感谢任何见解!
回答
有关 David 回答的更多上下文:Angular updates DOM state based on a reactive form control disabled status。我认为正在发生的事情:angular 在 AppComponent
之前呈现 CustomFormInputComponent
并将组件呈现为禁用。然后呈现 AppComponent,并在启用 name
控件的情况下构建 form
。 Angular 然后取消禁用 DOM 输入元素(这是设计的行为)。
最佳答案
如果您使用的是 FormGroup,则不应禁用 HTML 模板中的表单。如果您尝试在 HTML 中与 FormControl 一起禁用,它将不起作用。相反,它应该在 FormGroup 中完成。试试这个:
template: `
<mat-form-field [formGroup]="form">
<input matInput placeholder='Name' [formControlName]="formControlName">
</mat-form-field>
`
和:
ngOnInit() {
this.form = this.fb.group({
name: new FormControl({ value: '', disabled: this.disabled })
});
}
还有……没什么大不了的,但是……您真的应该这样做:
public form: FormGroup;
代替:
public form: any;
也不要忘记导入
import { FormGroup, FormControl } from '@angular/forms';
顺便说一句,表单组声明中的名称应该与您在 HTML 中设置的任何内容相匹配。 所以:
<input formControlName="myInputName">
和
this.form = this.fb.group({
myInputName....
});
关于angular - 无法使用 [formControlName] 禁用 matInput 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48451206/