我试图访问我的HTML模板中的DOM元素,但是我遇到了一个问题:这个元素是以ngIf为条件的,因此我有以下错误“属性‘抽屉’在‘Component’类型上不存在”。
以下是我的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>
有什么办法可以叫#抽屉,即使它是有条件的?
我尝试使用“drawer.open():null”对其进行调理,但也得到了相同的错误。
谢谢
发布于 2022-03-02 14:51:16
最好的方法是隐藏它,而不是使用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>
这应该能行
而且,当抽屉不在的时候,你也不能用抽屉做事情。
<mat-sidenav #drawer id="drawer" *ngIf="condition">
...
</mat-sidenav>
ts
const element: HTMLElement = document.getElementById('drawer') as HTMLElement;
if (element) {
// do things with drawer
}
https://stackoverflow.com/questions/71324661
复制相似问题