我只是需要在路由和应用程序根路由之间切换。我使用以下指令添加了该功能:
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);
}
}
}