情况如下:我有一个具有这种结构的组件:
<app>
<ng-container *ngIf="flag">
<component-one> </component-one>
<component-two> </component-two>
<component-three> </component-three>
</ng-container>
</app>
有一个服务(serviceGeneral)包含一个通用表单( formgroup )。
在 app 组件中,在某个方法中,将flag更改为 true。将标志更改为 true 后,相应地呈现组件(*ngIf 变为 true)。每个组件初始化的时候,对应的formgroup被添加到大表单的通用服务中(即component-one组件初始化时,该组件的formgroup字段被添加到通用表单中)。将 flag 标志更改为 true 后,我指定serviceGeneral表单的逻辑。
问题:更改标志后,组件尚未呈现(由于尚未将新字段添加到整个表单中),因此我无法处理表单。
解决方案:更改标志后将您的逻辑包装在 setTimeout() 中。
问题:有没有更优雅的方法来解决我的问题?没有 setTimeout ?或者这是最好的解决方案?
method() {
this.flag = true;
let groups = this.generalFormService.form;
...
}
我的决定:
method() {
this.flag = true;
setTimeout( () => {
let groups = this.generalFormService.form;
}, 0);
...
}