我需要将事件侦听器添加到 ng-template
或 *ngTemplateOutlet
的内容中,而不知道内容可能是什么。它可能是按钮或一些自定义组件。
我尝试访问 elementRef
,但这是不起作用的,因为它是一个注释节点。
当我通过ViewContainerRef.createEmbeddedView
添加TemplateRef
时,我找不到对添加视图的元素参考的任何访问。
我尝试的另一种方式是通过我的组件中的@ViewChild("foo")
和使用模板出口来访问它。没有成功。
<ng-container #foo *ngTemplateOutlet="foo"></ng-container>
有人有任何建议吗?
编辑:
我有一个组件,我希望消费者选择以相同的方式为孩子提供定制图标。
<mat-vertical-stepper>
<ng-template matStepperIcon="edit">
<custom-icon>edit</custom-icon>
</ng-template>
<ng-template matStepperIcon="done">
<custom-icon>done</custom-icon>
</ng-template>
</mat-vertical-stepper>
查看此示例,我需要访问<custom-icon>
并在其中添加事件处理程序,而实际上不知道它是<custom-icon>
。
创建属性指令,然后向其添加@hostlistener。这是一个示例
import { Directive, ElementRef, OnInit, Renderer2, HostListener, HostBinding, Input } from "@angular/core";
@Directive({
selector: '[appHighLight]'
})
export class HighLightDirective implements OnInit {
@Input() defaultColor: string ='transparent';
@Input() highLightColor: string ='blue';
@HostBinding('style.backgroundColor') backgroundColor: string;
constructor(private elementRef: ElementRef, private renderer: Renderer2) { }
ngOnInit(){
this.backgroundColor = this.defaultColor;
}
@HostListener('mouseenter') mouseIn(eventData : Event){
this.backgroundColor = this.highLightColor;
}
@HostListener('mouseleave') mouseOut(eventData : Event){
this.backgroundColor = this.defaultColor;
}
}