Angular使用组件时遇到的一些错误整理
电脑版发表于:2019/11/4 14:57
先看看代码
export class SidenavComponent implements OnInit {
private mediaMatcher: MediaQueryList = matchMedia(`(max-width: ${SMALL_WIDTH_BREAKPOINT}px)`);
constructor(
private router: Router,
zone: NgZone) {
this.mediaMatcher.addListener(mql => zone.run(() => this.mediaMatcher = mql));
}
@ViewChild(MatDrawer) drawer: MatDrawer;
ngOnInit() {
this.router.events.subscribe(() => {
if (this.isScreenSmall()) {
this.drawer.close();
}
});
}
isScreenSmall(): boolean {
return this.mediaMatcher.matches;
}
}看着没什么错
实际根据版本的不同会有问题
(1)this未明确指明某对象
this.mediaMatcher.addListener(mql => zone.run(() => this.mediaMatcher = mql));
需改成
this.mediaMatcher.addListener(mql => {
zone.run((x) =>x.mediaMatcher = mql)
});(2)这里也是更具版本的不同也会遇到问题
@ViewChild(MatDrawer) drawer: MatDrawer;
需改成
@ViewChild(MatDrawer,{ static:true }) drawer: MatDrawer;后续会写一些Angluar多路由配置



