我正在使用 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();
}
使用
[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();
});