【问题标题】:ViewContainerRef not loading component into DOMViewContainerRef 未将组件加载到 DOM 中
【发布时间】:2016-08-22 21:04:00
【问题描述】:
@Component({
  selector: 'my-cmp',
  template: `
  <div #target></div>
  `
})
export class MyCmp {
@ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef;

render() {
    let cmp = Component(metadata)(type);
    this.componentResolver.resolveComponent(cmp).then(factory => {
      let component = this.target.createComponent(factory, 0, null, null);
    });
  }
}

我正在尝试将组件加载到ViewContainerRef。所有documentation 都表示,一旦创建了组件,它就会自动加载到DOM(ViewChild 所在的位置。)但这并没有发生。为什么?请帮忙。

【问题讨论】:

    标签: javascript angularjs angular


    【解决方案1】:

    不确定您添加的代码是完整的还是其中的一部分,我没有看到 ComponentResolver 注入到您的构造函数中,这里也可能是错字但resolveComponent 然后块没有关闭(缺少)) .

     import { Component, ViewChild, ViewContainerRef, ComponentResolver }  from '@angular/core';
    
     @Component({
       selector: 'my-test',
       template: `
        Test Component
       `
     })
     export class TestComponent {}
    
     @Component({
       selector: 'my-app',
       template: `<h3 class="title">Basic Angular 2</h3>
       <div #target></div>
       `
     })
     export class AppComponent {
       @ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef;
    
       constructor(private componentResolver: ComponentResolver){
         this.render();
       }
    
       render = () =>  {
         // include app specific logic to get ComponentType
         //  let cmp = Component(metadata)(type);
         this.componentResolver.resolveComponent(TestComponent).then(factory => {
          let component = this.target.createComponent(factory, 0, null, null);
         });
        }
      }
    

    这里是Plunker!!

    希望这会有所帮助!

    【讨论】:

    • 在我的来源中,我已经纠正了所有错别字哈哈。我上面的例子并不完整,因为完整的版本要长得多。不幸的是我仍然有这个问题......
    • 你检查过plunker吗?你可以为你的代码创建一个 plunker 你有任何错误吗?
    【解决方案2】:
    @Component({
      selector: 'my-app',
      providers: [],
      template: `
        <div>
          <h2>Dynamicaly Add Elements</h2>
          <button (click)="addItem()">add hello</button>
          <div #placeholder></div>
        </div>
      `,
      entryComponents: [HelloComponent]
    })
    export class App {
      @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef;
      private componentFactory: ComponentFactory<any>;
    
      constructor(componentFactoryResolver: ComponentFactoryResolver, compiler: Compiler) {
        this.componentFactory = componentFactoryResolver.resolveComponentFactory(HelloComponent);
        //this.componentFactory = compiler.compileComponentSync(HelloComponent);
      }
    
      addItem () {
        this.viewContainerRef.createComponent(this.componentFactory, 0);
      }
    }
    

    Plunker example

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2020-01-04
      • 1970-01-01
      • 2020-08-30
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 2019-03-17
      相关资源
      最近更新 更多