【发布时间】:2021-10-26 14:38:27
【问题描述】:
我在尝试实现一个指令时遇到了麻烦,我可以在具有 [formGroup] 属性的元素上使用该指令来设置禁用整个表单组及其表单控件的条件,而不是强制调用 this.formGroup.disable()。
我有一个通过搜索网络获得的表单控件的工作指令:
import { Directive, Input } from "@angular/core";
import { NgControl } from "@angular/forms";
// use this directive instead manually enabling and disabling with reactive forms
@Directive({
selector: "([formControlName], [formControl])[disabledControl]",
})
export class DisabledControlDirective {
@Input() set disabledControl(condition: boolean) {
if (this.disabled !== undefined) {
this.toggleControl(condition);
}
this.disabled = condition;
}
disabled: boolean;
constructor(private readonly ngControl: NgControl) {}
ngOnInit() {
this.toggleControl(this.disabled);
}
toggleControl(condition: boolean) {
const action = condition ? "disable" : "enable";
this.ngControl.control[action]();
}
}
我为表单组尝试了类似的方法:
import { Directive, Input } from "@angular/core";
import { ControlContainer } from "@angular/forms";
@Directive({
selector: "([formGroup])[disabledGroup]",
})
export class DisabledGroupDirective {
@Input() set disabledGroup(condition: boolean) {
if (this.disabled !== undefined) {
this.toggleGroup(condition);
}
this.disabled = condition;
}
disabled: boolean;
constructor(private readonly controlContainer: ControlContainer) {}
ngOnInit() {
this.toggleGroup(this.disabled);
}
toggleGroup(condition: boolean) {
const action = condition ? "disable" : "enable";
this.controlContainer.control[action]();
}
}
但表单组实际上并没有正确禁用。我在 toggleGroup() 方法上设置了一个断点,之后表单组的状态为“已禁用”,但在恢复应用程序时,表单完成加载并且未被禁用。我随后通过单击按钮将表单组注销,状态再次为“无效”,而不是“禁用”。
有解决这个问题的想法吗?
编辑: 我对此做了一个非常基本的 Stackblitz,它似乎可以自己工作: https://stackblitz.com/edit/angular-ivy-owlvqu?file=src/app/app.component.ts
编辑2: 没有其他东西可以操纵该表单组,除了有一次它是通过 ngOnInit() 中的 addControl() 添加到父 formGroup 的,但即使在 stackblitz 中取消禁用仍然不起作用,我可以不知道什么可能会重置其状态。
我尝试在 group 指令中使用 ngAfterViewInit() 而不是 ngOnInit(),奇怪的是,它有效,但它禁用了。我不知道这是否是最干净的解决方案,最好知道 formGroup 会进一步发生什么,但我的代码中没有任何东西可以操纵它。
【问题讨论】:
标签: angular typescript angular-reactive-forms angular-directive