角元素注入器不适用于ng-content

时间:2018-12-03 17:15:34

标签: javascript angular

我有一个父级组件:

@Component({
  selector: 'parent',
  template: '<ng-content></ng-content>'
})
export class ParentComponent {}

还有一个注入ParentComponent的孩子:

@Component({
  selector: 'child'
})
export class ChildComponent {

  constructor(private parent: ParentComponent) {}

}

如果我直接在模板中使用父母和孩子,例如:

<parent>
  <child></child>
</parent>

它工作正常,我在孩子体内得到了ParentComponent。但是,如果我需要通过child获取ng-content,例如:

@Component({
  selector: 'other-comp',
  template: `
    <parent>
      <ng-content></ng-content> 
    </parent>
  `,
})
export class OtherCompComponent {}

// app.html
<other-comp>
  <child></child>
</other-comp>

它引发错误:

  

NullInjectorError:没有ParentComponent的提供者!

为什么它不再工作了?

0 个答案:

没有答案