I'm trying to limit the search of my dependencies to only its host by using @Host
.
But it's not working without ng-content
or transclusion.
The below code is not working(without 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;
}
}
With ng-content
Now just by changing the templates in RootComponent
& the ParentComponent
the above code starts working
@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;
}
}
Questions:
- Why the first code not working(without ng-content)..?
- @Host can only works with ng-content..?
- What difference ng-content makes as the structure of the compiled HTML is same in both the cases.
Here are the Plunker for reference: