ReflectiveInjector不与ngComponentOutlet指令正确实例化成分(Ref

2019-09-29 08:11发布

下面是一个例子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!');
  }
}

Answer 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"}}}'

叉形Plunker



文章来源: ReflectiveInjector is not instantiating component correctly with ngComponentOutlet Directive