我在启用和禁用我的应用程序中的表单控件时遇到问题。这可能是因为表单在异步上下文中被启用/禁用。
代码如下。
user.component.html
<form [formGroup]="form">
<input type="text" id="name" formControlName="name" />
<input type="text" id="age" formControlName="age" />
</form>
user.component.ts
ngOnInit() {
this._route.queryParams.subscribe(params => {
getUser(params.userId).subscribe(user => {
this._buildForm(user);
})
});
}
private _buildForm(user){
this.form = _fb.group({
name: [{value: user.name, disabled: user.someCondition}, Validators.required],
age: [{value: user.age, disabled: user.anotherCondition}, Validators.required]
})
}
当用户第一次加载参数更改时,控件会根据相关条件启用/禁用。当参数随后发生变化时,尽管值已适当设置,但控件的状态保持不变。
我尝试了不同的方法来解决这个问题,但没有任何帮助。例如,我在 _buildForm
方法的末尾尝试了以下内容。
this.form.disable() //Doesn't do anything
this.form.controls.name.disable(); //Doesn't help
以下是按预期工作的一件事(但这不是必需的)。
<button (click)="form.disable()" value="Disable Form" />
<button (click)="form.enable()" value="Enable Form" />
我觉得问题出在 _buildForm()
是从异步上下文(订阅方法)中调用的。
我该如何解决这个问题?
更新
请注意,Observable 订阅是在导航的基础上触发的,如下所示。
this._router.navigate([], {
relativeTo: this._route,
queryParams: {userId: 10}
})
更新 2 https://angular-cvf1fp.stackblitz.io
这是一种更容易理解我的问题的方法
最佳答案
您只需要启用/禁用表单控件的方法。
这里是 stackblitz example .效果很好。
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
group;
isDisabled = true;
constructor(fb: FormBuilder) {
this.group = fb.group({
stuff: fb.control({value: 'stuff', disabled: this.isDisabled})
});
}
toggle() {
this.isDisabled = !this.isDisabled;
this.group.controls.stuff[this.isDisabled ? 'enable' : 'disable']();
}
}
关于javascript - Angular 4 - react 形式启用/禁用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50049715/