使用@host获得宿主元素注入器里注入的内容

container Component:
使用@host获得宿主元素注入器里注入的内容

<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里注入器注入的实例:

使用@host获得宿主元素注入器里注入的内容

更多Jerry的原创文章,尽在:“汪子熙”:
使用@host获得宿主元素注入器里注入的内容

上一篇:PHP装饰器模式


下一篇:粗浅聊聊Python装饰器