在Angular中,routerLink只会触发一次ngOnInit的问题可以通过以下解决方法解决:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Link
`,
})
export class ExampleComponent implements OnInit {
ngOnInit() {
this.rla.isActive.subscribe((value: boolean) => {
if (value) {
// 执行相应的逻辑
}
});
}
}
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-example',
template: `
Link
`,
})
export class ExampleComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd && event.url === '/example') {
// 执行相应的逻辑
}
});
}
}
这两种解决方法都可以在routerLink被点击时执行相应的逻辑,而不仅限于ngOnInit方法。