ReflectiveInjector is not instantiating component correctly with ngComponentOutlet Directive

浪子不回头ぞ 提交于 2020-01-05 08:17:23

问题


Here is an example Plunker. Any help is appreciated!

@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:


I don't see Component2 property in Component1. So you're passing undefined to *ngComponentOutlet

Try the following

export class Component1 implements OnInit{
  Component2 = Component2;

And you have syntax error

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

you should use it as

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

Forked Plunker



来源:https://stackoverflow.com/questions/44281288/reflectiveinjector-is-not-instantiating-component-correctly-with-ngcomponentoutl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!