简体   繁体   English

是否可以直接从模板中获取 nativeElement 引用?

[英]Is it possible to get nativeElement reference directly from the template?

I want to get native host element of the mat-checkbox so I can do itemCheckbox.click() .我想获取mat-checkbox的本机主机元素,以便可以执行itemCheckbox.click() Now, itemCheckbox is a MatCheckbox .现在, itemCheckbox是一个MatCheckbox Can I get reference to the native element directly in the template ?我可以直接在模板中获取对本机元素的引用吗?

  <mat-checkbox
                #itemCheckbox
                (click)="$event.stopPropagation()"
                (change)="$event ? selection.toggle(row) : null"
                [checked]="selection.isSelected(row)">
  </mat-checkbox>

ideally I would imagine something like this理想情况下,我会想象这样的事情

<our-component #item="ElementRef"></our-component> 

PS. PS。 this is generic question.这是一个通用问题。 I know I can itemCheckbox.toggle() but the point is to get native element reference of the component in general.我知道我可以itemCheckbox.toggle()但关键是要获取组件的本机元素引用。 Also, I know I can @ViewChild given component and get native element from there, but that is not the point.另外,我知道我可以@ViewChild给定组件并从那里获取本机元素,但这不是重点。

you can use @viewChild() for that purpose like the following:您可以为此目的使用 @viewChild() ,如下所示:

@ViewChild('itemCheckbox') private itemCheckbox: MatCheckbox;

keep that in mind to import viewchild and MatCheckbox like this:请记住,像这样导入viewchildMatCheckbox

import { ViewChild } from '@angular/core';
import { MatCheckbox } from '@angular/material';

then you can access that in your code:然后你可以在你的代码中访问它:

this.itemCheckbox.checked

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM