How do I find Element inside TemplateRef
我一直在四处搜寻,但对角度5/6还是有点陌生,但我正在尝试看看是否有可能。
问题
说我有一个模板:
1 2 3 4 | <ng-template #rt let-r="result" let-t="term"> <ngb-highlight [result]="r.typeAheadDisplayName" [term]="t"></ngb-highlight> <span *ngIf="r.primaryName">(alias for {{ r.primaryName }}) </span>{{ r.metaData }} </ng-template> |
在此模板内,将生成一个按钮,可用作选择选项的一种方法。 但是,由于给定的原因,我需要能够定位按钮数组的
我知道我可以选择要执行的元素/模板:
1 | @ViewChild('rt') rt : TemplateRef; |
但是,实际上我是否可以执行类似于jQuery
1 2 3 4 5 6 7 8 | @Component() export class MyComponent implements OnInit { @ViewChild('rt') rt : ElementRef; ngOnInit() { const childNode = this.rt.nativeElement.querySelector('.child-class'); } } |
更新:
要使用
1 2 3 4 5 6 7 8 9 10 | <ng-template [ngTemplateOutlet]="rt"></ng-template> @Component({selector: 'my-component'}) export class MyComponent implements OnInit { @ContentChild('rt') rt: TemplateRef; ngOnInit() { const childNode = this.rt.elementRef.nativeElement.querySelector('.foo'); } } |
现在,您可以像这样使用该组件:
1 2 3 4 5 | <my-component> <ng-template #rt> Hello world </ng-template> </my-component> |