简体   繁体   English

HTML 中的条件访问(使用 ngIf)DOM 元素 Angular 中的模板

[英]Access conditioned (with ngIf) DOM element in HTML template in Angular

I'm trying to access a DOM element within my HTML template, but I got a problem: this element is conditioned with ngIf, and so I have the following error "Property 'drawer' does not exist on type 'Component'".我试图访问我的 HTML 模板中的一个 DOM 元素,但我遇到了一个问题:这个元素是用 ngIf 调节的,所以我有以下错误“属性‘抽屉’在‘组件’类型上不存在”。

Here is an extract from my HTML code:这是我的 HTML 代码的摘录:

<mat-sidenav-container>
    <mat-sidenav #drawer *ngIf="condition">
        ...
    </mat-sidenav>
    <mat-sidenav-content>
        <some-component (someEventEmitter)="drawer.open()"></some-component>
    </mat-sidenav-content>
</mat-sidenav-container>

Is there a solution to call #drawer even if it is conditioned?即使有条件,是否有调用#drawer 的解决方案?

I tried conditioning with "drawer? drawer.open(): null" but I got the same error.我尝试使用“drawer?drawer.open(): null”进行调节,但我遇到了同样的错误。

Thanks谢谢

The better way would be to hide it than using ngIf.更好的方法是隐藏它而不是使用 ngIf。

<mat-sidenav-container>
    <mat-sidenav #drawer [hidden]="!condition">
        ...
    </mat-sidenav>
    <mat-sidenav-content>
        <some-component (someEventEmitter)="drawer.open()">
    </mat-sidenav-content>
</mat-sidenav-container>

This should work这应该工作

Also you can always not do things with drawer while it's not there另外,当抽屉不在时,你总是不能用抽屉做事

<mat-sidenav #drawer id="drawer" *ngIf="condition">
  ...
</mat-sidenav>

ts TS

const element: HTMLElement = document.getElementById('drawer') as HTMLElement;

if (element) {
  // do things with drawer
}

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

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