可以设置一个变量来存储导航栏的状态,当路由发生变化时,判断是否需要折叠导航栏。示例代码如下:
在 ts 文件中:
import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-navigation-menu',
templateUrl: './navigation-menu.component.html',
styleUrls: ['./navigation-menu.component.css']
})
export class NavigationMenuComponent {
isCollapsed: boolean = false;
constructor(private router: Router) {
// 监听路由事件
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
// 根据路由判断是否需要折叠导航栏
if (event.url == '/home') {
this.isCollapsed = false;
} else {
this.isCollapsed = true;
}
}
});
}
}
在模板文件中:
在这个示例中,我们在导航组件中添加了一个变量 isCollapsed 来存储导航栏的状态,然后监听路由事件,当发生路由变化时根据当前路由来判断是否需要折叠导航栏。在模板文件中,我们使用 Angular 自带的属性绑定语法来绑定 isCollapsed 变量到导航栏的折叠状态上,使得当变量的值改变时,导航栏的状态也随之改变。