我有一个ComponentA:
@Component({
selector: 'component-a',
template: `<span>{{sampleText}}</span>`,
styles: []
})
export class ComponentA implements OnInit {
sampleText: string = 'ComponentA';
constructor() {}
ngOnInit() {
}
}
和ComponentA的指令:
@Directive({
selector: '[DirectiveForA]'
})
export class DirectiveForA implements OnInit {
@Input('customText') customText: string;
constructor(private componentA: ComponentA) {
}
ngOnInit() {
this.componentA.sampleText = this.customText;
}
}
我可以为其应用指令:
<component-a>
<ng-template DirectiveForA customText="injectedText"></ng-template>
</component-a>
但是然后,我有另一个ComponentB,里面有一个ComponentA:
@Component({
selector: 'component-b',
template: `<component-a></component-a>`,
styles: []
})
export class ComponentB implements OnInit {
@ViewChild(ComponentA, { static: false }) componentA: ComponentA;
constructor() {}
ngOnInit() {
}
}
当我像这样使用ComponentB时,我想将指令应用于内部的ComponentA:
<component-b>
<ng-template DirectiveForA customText="injectedText!"></ng-template>
</component-b>
Angular在抱怨:
ERROR NullInjectorError: StaticInjectorError(AppModule)[DirectiveForA -> ComponentA]:
StaticInjectorError(Platform: core)[DirectiveForA -> ComponentA]:
NullInjectorError: No provider for ComponentA!
问题:我有办法使它起作用吗?如果没有,什么是更好的做法?(在我的情况下,ComponentA实际上是一个网格,DirectiveA是某个网格列的模板。ComponentB实际上是具有输入形式的网格。ComponentB经常使用,但是我想在ComponentA内部自定义列。)
我终于找到了一种使用可选注射的方法。