ReflectiveInjector未使用ngComponentOutlet指令正确实例化组件

时间:2017-05-31 09:44:52

标签: angular angularjs-directive

以下是Plunker示例。任何帮助表示赞赏!

@Component({
  selector: 'component1',
  template : `
    <h3>{{title}}</h3>
    <button (click)='dismiss()'>dismiss</button>
     <ng-container *ngComponentOutlet="Component2;
              injector: myInjector;
              content: myContent">
    </ng-container>
  `
})
export class Component1 implements OnInit{
  title : string = "hello!";
  myInjector: Injector;
  myContent: any;
  constructor(private injector : Injector){
    this.myInjector = ReflectiveInjector.resolveAndCreate([
        { provide : Component2, useClass : Component2 }, 
        { provide: TestObject, useFactory: ()=> 
          { 
            return new TestObject("123", "hello world!", "<h2>sample</h2>", "{"a":{"b":{"Value":"test"},"c":{"Value":"test 1"}}}");
          }
        }
      ], this.injector);
  }

  ngOnInit(){
    var templateParent = document.createElement("div");
    templateParent.innerHTML = "<h2>this is test html!</h2>";
    this.myContent = [templateParent.childNodes];


  }

  dismiss(){
    console.log('dismiss clicked!');
  }
}

1 个答案:

答案 0 :(得分:1)

我在Component2中看不到Component1财产。因此,您已将undefined传递给*ngComponentOutlet

尝试以下

export class Component1 implements OnInit{
  Component2 = Component2;

你有语法错误

"{"a":{"b":{"Value":"test"},"c":{"Value":"test 1"}}}"

你应该用它作为

'{"a":{"b":{"Value":"test"},"c":{"Value":"test 1"}}}'

<强> Forked Plunker

相关问题