一种编程方式是在组件本身中执行此操作。我在这个问题上苦苦挣扎了三个星期,但放弃了有角度的文档,而是阅读了使routerlinkactive工作的实际代码,这就是我能找到的最佳文档。
import {
Component,AfterContentInit,OnDestroy, ViewChild,OnInit, ViewChildren, AfterViewInit, ElementRef, Renderer2, QueryList,NgZone,ApplicationRef
}
from '@angular/core';
import { Location } from '@angular/common';
import { Subscription } from 'rxjs';
import {
ActivatedRoute,ResolveStart,Event, Router,RouterEvent, NavigationEnd, UrlSegment
} from '@angular/router';
import { Observable } from "rxjs";
import * as $ from 'jquery';
import { pairwise, map } from 'rxjs/operators';
import { filter } from 'rxjs/operators';
import {PageHandleService} from '../pageHandling.service'
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements AfterContentInit,AfterViewInit,OnInit,OnDestroy{
public previousUrl: any;
private subscription: Subscription;
@ViewChild("superclass", { static: false } as any) superclass: ElementRef;
@ViewChildren("megaclass") megaclass: QueryList<ElementRef>;
constructor( private element: ElementRef, private renderer: Renderer2, private router: Router, private activatedRoute: ActivatedRoute, private location: Location, private pageHandleService: PageHandleService){
this.subscription = router.events.subscribe((s: Event) => {
if (s instanceof NavigationEnd) {
this.update();
}
});
}
ngOnInit(){
}
ngAfterViewInit() {
}
ngAfterContentInit(){
}
private update(): void {
if (!this.router.navigated || !this.superclass) return;
Promise.resolve().then(() => {
this.previousUrl = this.router.url
this.megaclass.toArray().forEach( (superclass) => {
var superclass = superclass
console.log( superclass.nativeElement.children[0].classList )
console.log( superclass.nativeElement.children )
if (this.previousUrl == superclass.nativeElement.getAttribute("routerLink")) {
this.renderer.addClass(superclass.nativeElement.children[0], "box")
console.log("add class")
} else {
this.renderer.removeClass(superclass.nativeElement.children[0], "box")
console.log("remove class")
}
});
})
//update is done
}
ngOnDestroy(): void { this.subscription.unsubscribe(); }
//class is done
}
注意:
对于编程方式,请确保添加router-link并且它带有子元素。如果要更改此设置,则需要摆脱上的子项superclass.nativeElement
。
@input
for选项,但是exact: false
只要当前路由的同级也处于活动状态就激活该类。