2017-05-31 74 views
1

下面是一個示例Plunker。任何幫助表示讚賞!ReflectiveInjector沒有正確使用ngComponentOutlet指令實例化組件

@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!'); 
    } 
} 
+0

將鏈接從代碼塊移動到鏈接,將相關代碼從plunker複製到問題 –

回答

1

我沒有看到Component1Component2財產。所以,你傳遞給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