本文介绍了ReflectiveInjector无法使用ngComponentOutlet指令正确实例化组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个示例柱塞.感谢您的帮助!

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

推荐答案

我在Component1中看不到Component2属性.因此,您要将undefined传递给*ngComponentOutlet

I don't see Component2 property in Component1. So you're passing undefined to *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

这篇关于ReflectiveInjector无法使用ngComponentOutlet指令正确实例化组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 00:48