我想你是在问我怎么才能从Directive's主机Component那里得到TemplateRef分?
如果事先知道组件的类型,则可以直接从指令中引用它:
export class Directive1Directive implements AfterViewInit {
constructor(@Host() @Self() private host: Component1Component) {}
ngAvterViewInit(): void {
console.log(this.host.templateRef);
}
}
如果您不知道预期的宿主组件的类型,则会变得更加棘手.一般而言,将主机组件注入指令的最佳方式是让该主机指令实现一个类,并将该组件作为该类提供.
您可以从创建一个具有要引用的宿主构件的所有属性的类开始.在本例中,我们只声明公开TemplateRef的属性.在接口上使用类的唯一原因是它减少了使用InjectionToken的需要.
export abstract class BaseComponent {
public templateRef?: TemplateRef<any>;
}
主机组件中唯一的问题是,我们需要将一个提供程序添加到它的提供程序数组中,该数组基本上以别名BaseComponent"重新提供"自己.函数forwardRef用于创建对稍后声明的内容的延迟引用.
@Component({
/*...*/
providers: [{ provide: BaseClass, useExisting: forwardRef(() => Component1Component ) }]
})
export class Component1Component implements BaseComponent {
@ViewChild('content') public templateRef?: TemplateRef<any>;
}
该指令基本没有变化.
export class Directive1Directive implements AfterViewInit {
constructor(private host: BaseComponent) {}
ngAvterViewInit(): void {
console.log(this.host.templateRef);
}
}
这个答案中有很大一部分来自How You Can Access All Host Component Details Inside the Directive in Angular人.