我正在创建一个Web应用程序,它将从角度4的另一个页面加载侧边菜单。 我在这里定义了带有routerLink的菜单按钮。
<a class="menu-button"routerLink="/menu">
<div class="menu" >
<div class="bar" id="bar-1"></div>
<div class="bar" id="bar-2"></div>
<div class="bar" id="bar-3"></div>
</div>
</a>
即使菜单打开,导航栏也会显示,我想知道在菜单打开时是否有一种方法可以将angularLink从“/ menu”切换到“/ home”。
答案 0 :(得分:0)
不确定是否回答了你的问题,
但您可以使用routerLinkActive
指令来检查哪条路线是活动的,并根据该隐藏或显示相应的链接。
检查以下实施,
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>
<hr />
<a routerLink="/home" [ngClass]="{'hide': !menu.isActive}"
routerLinkActive #home="routerLinkActive" >Home</a>
<a routerLink="/menu" [ngClass]="{'hide': !home.isActive}"
routerLinkActive #menu="routerLinkActive" >Menu</a>
<hr />
<router-outlet></router-outlet>
`,
styles:[
`
.hide{
display: none;
}
`
]
})
class AppComponent { name = 'Angular'; }
这是Plunker !!
希望这会有所帮助!!
答案 1 :(得分:0)
我只需要在路线和app根路线之间切换。我使用以下指令添加了该功能:
import { Directive, HostListener, Input, Self } from '@angular/core';
import { RouterLink, Router } from '@angular/router';
/**
* This directive adds the ability to toggle a route with Angular's
* {@link RouterLink} directive.
*
* ### Example:
* ```html
* <button routerLink="/my-path" routerLinkToggle></button>
* ```
* The example above creates a toggle button that navigates between
* `http://localhost/my-path` and `http://localhost`.
*/
@Directive({
selector: '[routerLinkToggle]'
})
export class RouterLinkToggleDirective {
/**
* The {@link RouterLink.onClick} method.
*/
private readonly _onClick: () => boolean;
/**
* Navigation commands.
*/
private commands: any[] = [];
constructor(@Self() private routerLink: RouterLink,
private router: Router) {
// Keep a reference to the original `routerLink.onClick` method.
this._onClick = this.routerLink.onClick;
// Replace the `routerLink.onClick` method with a dummy method.
// This is needed because the order in which directives on the
// same host element are executed is undefined. By overwriting
// routerLink's onClick method but keeping a reference to it, we
// now have control over when it will be called.
this.routerLink.onClick = () => true;
}
/**
* Set the path of the route that you want to toggle to. If no path
* is provided, the directive navigates to the root of the app.
*/
@Input()
set routerLinkToggle(commands: any[] | string) {
if (commands != null) {
this.commands = Array.isArray(commands) ? commands : [commands];
} else {
this.commands = [];
}
}
@HostListener('click')
onClick() {
if (this.router.isActive(this.routerLink.urlTree, true)) {
this.router.navigate(this.commands);
} else {
// Call the `_onClick` method within its original `routerLink` conext.
this._onClick.call(this.routerLink);
}
}
}