概述
container Component:
<app-host-decorator appHostDecorator>
<app-host-decorator-child></app-host-decorator-child>
</app-host-decorator>
app-host-decorator的实现:
import {Component} from '@angular/core';
import {HostComponentService} from './host-component.service';
import {TOKEN_HOST_CLASS_PROVIDER} from '../parameter-decorator-constant';
import {HostTokenComponentService} from './host-token-component.service';
@Component({
selector: 'app-host-decorator',
template: `
<h3>@Host -- 获取宿主元素注入器里面注入的对象</h3>
<ng-content></ng-content>
`,
providers: [
HostComponentService,
{provide: TOKEN_HOST_CLASS_PROVIDER, useClass: HostTokenComponentService}
]
})
export class HostDecoratorComponent {
}
app-host-decorator-child的实现,该child Component的template内容,会显示在parent Component的ng-content里:
import {Component, Host, Inject} from '@angular/core';
import {HostComponentService} from './host-component.service';
import {TOKEN_HOST_CLASS_PROVIDER} from '../parameter-decorator-constant';
import {HostTokenComponentService} from './host-token-component.service';
@Component({
selector: 'app-host-decorator-child',
template: `
<p>child Component里,ng-content对应的内容</p>
`
})
export class HostDecoratorChildComponent {
constructor(@Host() private componentService: HostComponentService,
@Host() @Inject(TOKEN_HOST_CLASS_PROVIDER) private tokenService: HostTokenComponentService) {
}
}
消费该Component的HTML代码:
<app-host-decorator appHostDecorator>
<!--
<app-host-decorator-child></app-host-decorator-child>
-->
</app-host-decorator>
Directive的代码:
import {Directive, Host, Inject} from '@angular/core';
import {HostComponentService} from './host-component.service';
import {TOKEN_HOST_CLASS_PROVIDER} from '../parameter-decorator-constant';
import {HostTokenComponentService} from './host-token-component.service';
@Directive({
selector: '[appHostDecorator]'
})
export class HostDecoratorDirective {
/**
* @Host() 获取宿主元素里面提供的服务(宿主元素注入器提供的服务)
* @param componentService
* @param tokenService
*/
constructor(@Host() private componentService: HostComponentService,
@Host() @Inject(TOKEN_HOST_CLASS_PROVIDER) private tokenService: HostTokenComponentService) {
console.log('in host Decorator directive: ',
componentService, tokenService);
}
}
运行时我们能发现,无论是在Directive里还是在child Component里,我们使用@host,都能拿到 host Component里注入器注入的实例:
更多Jerry的原创文章,尽在:“汪子熙”:
最后
以上就是潇洒八宝粥为你收集整理的使用@host获得宿主元素注入器里注入的内容的全部内容,希望文章能够帮你解决使用@host获得宿主元素注入器里注入的内容所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复