只需将值绑定到href
属性而不是使用routerLink
指令。
<a [href]="'#'+sectionName">One</a>
或者您可以构建自己的指令:
@Directive({
selector: 'a[anchorLink]'
})
export class AnchorLinkDirective {
@Input()
@HostBinding('attr.href')
public get anchorLink() {
return '#' + this.link;
}
public set anchorLink(value: string) {
this.link = value;
}
@Input()
public anchorLinkActive: string;
private link: string;
private ngUnsubscribe$ = new Subject();
constructor(private router: Router, private renderer: Renderer2, private element: ElementRef) {
this.router.events.takeUntil(this.ngUnsubscribe$).subscribe(e => {
if(e instanceof NavigationEnd) {
let parts = e.urlAfterRedirects.split('#');
let element = this.element.nativeElement as HTMLElement;
if(this.anchorLinkActive && parts[parts.length - 1] === this.link) {
this.renderer.addClass(element, this.anchorLinkActive);
} else if(element.classList.contains(this.anchorLinkActive)) {
this.renderer.removeClass(element, this.anchorLinkActive);
}
}
});
}
ngOnDestroy() {
this.ngUnsubscribe$.next();
this.ngUnsubscribe$.complete();
}
}
注意:该指令非常基本,不包括anchorLinkActive
输入的更改。