我一直在搜寻,但是对角度5/6还是有点陌生,但是我正在尝试看看是否有可能。
问题
说我有一个模板:
<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>
Run Code Online (Sandbox Code Playgroud)
在此模板内,将生成一个按钮,可用作选择选项的一种方法。但是,由于给定的原因,我需要能够定位:first-child按钮数组。
我知道我可以选择要执行的元素/模板:
@ViewChild('rt') rt : TemplateRef<any>;
Run Code Online (Sandbox Code Playgroud)
但是,实际上我是否可以执行类似于jQuery的功能,.find甚至可以在AngularJS中执行相同的功能,以定位将在此模板内找到的元素。我一直在谷歌搜索,看不到找到答案。
nativeElement是您要寻找的。它将为您提供本机DOM节点,然后您可以使用诸如querySelector查询子节点之类的方法。
@Component()
export class MyComponent implements OnInit {
@ViewChild('rt') rt : ElementRef;
ngOnInit() {
const childNode = this.rt.nativeElement.querySelector('.child-class');
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
要使用ng-template,您可以将ContentChild和TemplateRef一起使用。TemplateRef仍然嵌入ElementRef其中,因此您仍然可以访问该nativeElement属性并执行所需的任何查询。
<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');
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以像这样使用该组件:
<my-component>
<ng-template #rt>
<div class="foo">Hello world</div>
</ng-template>
</my-component>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4883 次 |
| 最近记录: |