代码之家  ›  专栏  ›  技术社区  ›  zer0

角度6:生命周期挂钩问题中的CreateComponent

  •  1
  • zer0  · 技术社区  · 8 年前

    我正在尝试动态创建一个组件,并像这样设置Angular6代码

    HTML:

    <div *ngIf="defaultToTrue">
      <div #entry></div>
    </div>
    

    技术支持:

    在构造函数之前

    @ViewChild ('entry', {read: ViewContainerRef}) entry: ViewContainerRef;
    

    组件创建:

    const entryFormFactory = this.resolver.resolveComponentFactory(entryFormComponent);
    const entryComponent = this.entry.createComponent(entryFormFactory);`
    

    如果我把上面的两行放进去 ngAfterContentInit() ,我得到错误:

    错误:类型错误:无法读取未定义的属性“CreateComponent”

    如果我把它放进去 ngAfterViewInit() ,我得到错误:

    表达式在被检查后被更改

    只有当我把它包在 setTimeout 我不该这么做。

    我错过了什么?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Vega Stipe    8 年前

    标记有父模板变量的元素被包装在带有*ngif的DIV中。然而,*ngif将基于表达式从dom中移除元素。这意味着在创建类时,@viewchild正在引用一个未定义的、不存在的元素,生命周期挂钩尚未运行。
    我建议你用[隐藏的]来代替。

    Demo

    推荐文章