angular - Angular 2动态禁用FormControl
问题描述
我有一个简单的表单组,有 2 个表单控件。最初,这两个控件都需要验证。
我在模板中也有一个按钮。单击按钮时,我想更改表单组的行为。即,两个控件都需要被禁用和验证需要被删除。
import {
Component,
AfterViewInit,
ViewChild
} from '@angular/core';
import {
FormBuilder,
FormGroup,
Validators
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular 6';
form: FormGroup;
constructor(private fb: FormBuilder) {
let username = this.fb.control.apply(null, [{
value: 'gannr',
disabled: false
}, Validators.required])
let password = this.fb.control.apply(null, [{
value: 'hello',
disabled: false
}, Validators.required]);
this.form = this.fb.group({
username: username,
password: password
});
}
changeFormBehavior() {
let username = this.fb.control.apply(null, [{
value: 'gannr disabled',
disabled: true
}]);
let password = this.fb.control.apply(null, [{
value: 'hello',
disabled: true
}]);
this.form = this.fb.group({
username: username,
password: password
});
}
}
解决方案
也许如果你使用了正确的变量和语法......
changeFormBehavior() {
this.form.get('username').disable();
this.form.get('password').disable();
this.form.get('username').setValidators(null);
this.form.get('password').setValidators(null);
}