我如何在TemplateRef中找到Element [英] How do I find Element inside TemplateRef

查看:91
本文介绍了我如何在TemplateRef中找到Element的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜寻,但是对角度5/6还是有点陌生​​,但是我正在尝试看看是否有可能.

I've been googling around, and am still a bit new to angular 5/6, but I'm trying to see if something is possible.

问题

说我有一个模板:

<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.

Within this template a button will generate that can be used as a means of chosing an option. However, for a given reason I need to be able to target :first-child of the array of buttons.

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

I know that I can select the element/template doing:

@ViewChild('rt') rt : TemplateRef<any>;

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

but, can I actually do a function similar to jQuery's .find or even the same in AngularJS, to target the elements that would be found inside of this template. I've been googling and can't see to find an answer.

推荐答案

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

nativeElement is what you're looking for. It will give you the native DOM node, and from that you can use methods like querySelector to query child nodes.

@Component()
export class MyComponent implements OnInit {
    @ViewChild('rt') rt : ElementRef;

    ngOnInit() {
        const childNode = this.rt.nativeElement.querySelector('.child-class');
    }
}

更新:

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

For using ng-template, you can use ContentChild and TemplateRef together. TemplateRef still has an embedded ElementRef within it, so you will still be able to access the nativeElement property and do whatever querying you want.

<ng-template [ngTemplateOutlet]="rt"></ng-template>

@Component({selector: 'my-component'})
export class MyComponent implements OnInit {
    @ContentChild('rt') rt: TemplateRef<any>;

    ngOnInit() {
        const childNode = this.rt.elementRef.nativeElement.querySelector('.foo');
    }
}

现在您可以像这样使用该组件了:

Now you can use that component like so:

<my-component>
    <ng-template #rt>
        <div class="foo">Hello world</div>
    </ng-template>
</my-component>

这篇关于我如何在TemplateRef中找到Element的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆