Sla*_* II 8 angular angular-forms
我的Angular应用程序中有几个自定义表单控件组件,它们实现了ControlValueAccessor
界面并且运行良好.
但是,当markAsPristine()
在父窗体上调用时,或直接在我的自定义控件上调用时,我需要更新它的状态:我的自定义控件实际上有内部控制,我也需要调用markAsPristine()
它.
那么,我怎么知道什么时候markAsPristine()
被控制?
该ControlValueAccessor
接口没有成员,与此相关的问题,我可以实现.
Sla*_* II 10
经过彻底调查后,我发现Angular并未特别提供此功能.我在官方存储库中发布了一个有关此问题的问题,并且它获得了功能请求状态.我希望它能在不久的将来实施.
在此之前,这里有两种可能的解决方法:
markAsPristine()
@Component({
selector: 'my-custom-form-component',
templateUrl: './custom-form-component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: MyCustomFormComponent,
multi: true
}]
})
export class MyCustomFormComponent implements NG_VALUE_ACCESSOR, OnInit {
private control: AbstractControl;
ngOnInit () {
const self = this;
const origFunc = this.control.markAsPristine;
this.control.markAsPristine = function () {
origFunc.apply(this, arguments);
console.log('Marked as pristine!');
}
}
}
Run Code Online (Sandbox Code Playgroud)
ngDoCheck
请注意,此解决方案可能性能较差,但它可以为您提供更好的灵活性,因为您可以监控原始状态何时发生变化.在上面的解决方案中,只有在markAsPristine()
被呼叫时才会通知您.
@Component({
selector: 'my-custom-form-component',
templateUrl: './custom-form-component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: MyCustomFormComponent,
multi: true
}]
})
export class MyCustomFormComponent implements NG_VALUE_ACCESSOR, DoCheck {
private control: AbstractControl;
private pristine = true;
ngDoCheck (): void {
if (this.pristine !== this.control.pristine) {
this.pristine = this.control.pristine;
if (this.pristine) {
console.log('Marked as pristine!');
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您需要FormControl
从组件中访问该实例,请参阅以下问题:从Angular中的自定义表单组件访问FormControl.
归档时间: |
|
查看次数: |
4819 次 |
最近记录: |