首页 文章

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

提问于
浏览
7

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

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

我在此之后实施了一个解决方案:https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

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

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

错误:检查后表达式已更改 . 上一个值:'CD_INIT_VALUE' . 当前 Value :'测试项目 - 任务3' . 看起来这个视图是在其父级及其子级被脏检查后创建的 . 它是在变更检测钩子中创建的吗?

我仔细检查了所有步骤,我正在做同样的事情,你可以在那个教程上看到 .

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

预先感谢您的帮助!

EDIT: If I change the ngAfterViewInit to ngOnInit it all works... but according to the tutorial I should be using the first. Can anyone explain to me this? :-)

1 回答

  • 13

    错误说明了一切:

    看起来该视图是在其父级及其子级被脏检查后创建的 . 它是在变更检测钩子中创建的吗?

    您已动态创建组件(角度生命周期的“外部”),这意味着您需要手动控制更改检测 .

    这就是你需要做的事情:

    1)为它创建组件fireChanges()之后

    2)在处理分离()变化检测之前;

    以下是我的指令动态创建组件的示例:

    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

相关问题