关于angular:如何在TemplateRef中找到Element

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>

在此模板内,将生成一个按钮,可用作选择选项的一种方法。 但是,由于给定的原因,我需要能够定位按钮数组的:first-child

我知道我可以选择要执行的元素/模板:

1
@ViewChild('rt') rt : TemplateRef;

但是,实际上我是否可以执行类似于jQuery .find或甚至在AngularJS中相同的功能,以定位将在此模板内找到的元素。 我一直在谷歌搜索,看不到找到答案。


nativeElement是您要寻找的。 它将为您提供本机DOM节点,然后您可以使用querySelector之类的方法来查询子节点。

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');
    }
}

更新:

要使用ng-template,可以一起使用ContentChildTemplateRefTemplateRef仍具有嵌入的ElementRef,因此您仍然可以访问nativeElement属性并执行所需的任何查询。

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>