gpt4 book ai didi

Angular2动态内容加载抛出表达式更改异常

转载 作者:太空狗 更新时间:2023-10-29 17:12:26 26 4
gpt4 key购买 nike

我正在创建一个通用的甘特图可视化组件。

我将显示周数和任务的部分是通用的,但每一行都有一个标题,我希望它是动态的,例如,当显示每个用户的任务列表时,我想放置一些用户数据和一些操作按钮,但是当按项目显示任务时,我想显示项目数据和项目操作按钮。

我实现了以下解决方案:https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

一切似乎都运行良好,我看到每个场景中的操作按钮加载方式不同,但用户或项目数据却没有。此外,单击按钮上的 console.log(this.data.name),我在控制台中正确地看到了数据,但是如果我尝试在模板上打印 {{ data.name }}我什么也没看到。

我在控制台中看到以下错误:

Error: Expression has changed after it was checked. Previous value: 'CD_INIT_VALUE'. Current value: 'test project - Task 3 '. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook?

我仔细检查了所有步骤,我正在做与您在该教程中看到的完全相同的事情。

有谁知道该教程是否已过时?

提前感谢您的帮助!

编辑:如果我将 ngAfterViewInit 更改为 ngOnInit 一切正常......但根据教程我应该使用第一个。谁能给我解释一下? :-)

最佳答案

错误说明了一切:

It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook?

您已经动态创建了组件( Angular 生命周期的“外部”),这意味着您需要手动控制变更检测。

所以这就是你需要做的:

1) 创建组件后为其触发 detectChanges()

2)在配置detach()之前变化检测;

这是动态创建组件的指令示例:

export class ValidationMessageDirective implements AfterViewInit, OnDestroy {

private validationMessageComponent: ComponentRef<ValidationMessageComponent> = null;

ngAfterViewInit(): void {
let factory = this.componentFactoryResolver.resolveComponentFactory(this.vmComp);
this.ngOnDestroy();
this.validationMessageComponent = this.viewContainer.createComponent(factory, null, this.viewContainer.injector);
this.validationMessageComponent.changeDetectorRef.detectChanges();
}

ngOnDestroy(): void {
if (this.validationMessageComponent) {
this.validationMessageComponent.changeDetectorRef.detach();
//this.validationMessageComponent.destroy();
}
}

constructor(
private viewContainer: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver,
@Inject(ValidationMessageComponent) private vmComp: Type<ValidationMessageComponent>
) { }
}

相关问题:https://github.com/angular/angular/issues/11007

关于Angular2动态内容加载抛出表达式更改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42387348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com