角度4“在侧面菜单上使用* ngIf =“ sidemenuu == true”时无法读取未定义的属性'toggle'
side-menu.html
<button mat-icon-button (click)="snav.toggle()" value="sidebarclosed">
<mat-icon>menu</mat-icon>
</button>
<span fxFlex></span>
<app-header></app-header>
</mat-toolbar>
<mat-sidenav-container class="example-sidenav-container"
[style.marginTop.px]="mobileQuery.matches ? 0 : 0">
<mat-sidenav #snav id="snav" class="dark-sidebar pl-xs"
[mode]="mobileQuery.matches ? 'side' : 'over'" fixedTopGap="0"
[opened]="mobileQuery.matches" [disableClose]="mobileQuery.matches"
*ngIf="sidemenuu == true" >
<app-sidebar ></app-sidebar>
</mat-sidenav>
<mat-sidenav-content class="page-wrapper">
<div class="page-content">
<router-outlet>
<app-spinner></app-spinner>
</router-outlet>
</div>
</mat-sidenav-content>
</mat-sidenav-container>
这里正在查看location.path();具有indexOf('day'),然后将sidemenuu设置为false
side-menu.ts
export class SideMenuComponent implements OnDestroy, AfterViewInit {
mobileQuery: MediaQueryList;
url = '';
public sidemenuu: boolean = false;
private _mobileQueryListener: () => void;
constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher,
location: Location, router: Router, public menuItems: MenuItems) {
this.mobileQuery = media.matchMedia('(min-width: 768px)');
this._mobileQueryListener = () => changeDetectorRef.detectChanges();
this.mobileQuery.addListener(this._mobileQueryListener);
router.events.subscribe((val) => {
this.url = location.path();
this.sidemenuu = true;
if (((this.url.indexOf('day')) > -1)) {
this.sidemenuu = false;
} else {
this.sidemenuu = true;
}
});
}
ngOnDestroy(): void {
this.mobileQuery.removeListener(this._mobileQueryListener);
}
ngAfterViewInit() {
}
}
这是其他路径的错误
错误
SideMenuComponent.html:40错误TypeError:无法读取以下内容的属性“ toggle” 未定义
at Object.eval [as handleEvent] (SideMenuComponent.html:40)
at handleEvent (core.js:13589)
at callWithDebugContext (core.js:15098)
at Object.debugHandleEvent [as handleEvent] (core.js:14685)
at dispatchEvent (core.js:10004)
at eval (core.js:10629)
at HTMLButtonElement.eval (platform-browser.js:2628)
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4751)
at ZoneDelegate.invokeTask (zone.js:420)
答案 0 :(得分:1)
由于您的按钮位于mat-sidenav容器的“外部”,因此可以使用ViewChild
//In component.ts
@ViewChild('sidenav') sidenav:any;
toggleSidenav()
{
this.sidenav.toggle();
console.log(this.sidenav.toggle);
}
//In your .html
<button mat-icon-button (click)="toggleSidenav()" value="sidebarclosed">
答案 1 :(得分:1)
对于那些将跟进此问题的人员,将其添加到您的组件中。ts将解决此错误 @ViewChild('sidenav')sidenav:任何;
答案 2 :(得分:0)
可能是Viewchild问题。有时viewchild需要两个参数。 在这种情况下,您可以使用它。
@ViewChild('blabla', {static: false})