我正在尝试使用@Host
将我的依赖项搜索限制为仅限其主机。
但如果没有ng-content
或翻译,它就无法运作。
以下代码无效(没有ng-content)
// Root Component
@Component({
selector: 'my-app',
template: '<parent></parent>'
})
export class RootComponent { }
@Component({
selector: 'parent',
template: '<child></child>',
providers:[{provide:TestService,useClass:TestService}]
})
export class ParentComponent {
name: string = '';
constructor(abc:TestService){
abc.name='SomeName';
this.name=abc.name
}
}
@Component({
selector: 'child',
template: '<h1>{{parent}}</h1>'
})
export class ChildComponent {
parent: string = ""
constructor(@Host() testService: TestService) {
this.parent= 'My parent is :'+testService.name;
}
}
使用ng-content
现在只需更改RootComponent
&amp;中的模板即可ParentComponent
以上代码开始工作
@Component({
selector: 'my-app',
template: '<parent><child></child></parent>'
})
export class RootComponent { }
@Component({
selector: 'parent',
template: '<ng-content></ng-content>',
providers:[{provide:TestService,useClass:TestService}]
})
export class ParentComponent {
name: string = '';
constructor(abc:TestService){
abc.name='SomeName';
this.name=abc.name
}
}
@Component({
selector: 'child',
template: '<h1>{{parent}}</h1>'
})
export class ChildComponent {
parent: string = ""
constructor(@Host() testService: TestService) {
this.parent= 'My parent is :'+testService.name;
}
}
问题:
以下是Plunker供参考: