@Host — The @Host decorator tells DI to look for a dependency in any injector until it reaches the host
@Host example (source)
class OtherService {}
class HostService {}
@Directive({selector: 'child-directive'})
class ChildDirective {
logs: string[] = [];
constructor(@Optional() @Host() os: OtherService, @Optional() @Host() hs: HostService) {
// os is null: true
this.logs.push(`os is null: ${os === null}`);
// hs is an instance of HostService: true
this.logs.push(`hs is an instance of HostService: ${hs instanceof HostService}`);
}
}
@Component({
selector: 'parent-cmp',
viewProviders: [HostService],
template: '
',
})
class ParentCmp {
}
@Component({
selector: 'app',
viewProviders: [OtherService],
template: '
',
})
class App {
}