Angular的routerLink只会触发一次ngOnInit
创始人
2024-10-24 09:31:14
0

在Angular中,routerLink只会触发一次ngOnInit的问题可以通过以下解决方法解决:

  1. 使用routerLinkActive指令:routerLinkActive可以在当前路由激活时添加一个CSS类,我们可以利用这个特性来触发组件的变化。在组件的ngOnInit方法中,我们可以监听routerLinkActive指令的isActive属性,并根据isActive的值来执行相应的逻辑。
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) {
        // 执行相应的逻辑
      }
    });
  }
}
  1. 使用路由守卫:可以在路由守卫中监听路由变化,并在路由变化时执行相应的逻辑。
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方法。

相关内容

热门资讯

必备透视!德州透视是真的假的,... 您好,德州透视是真的假的这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多...
解迷透视!wpk德州局怎么透视... 解迷透视!wpk德州局怎么透视,微信微乐游戏辅助脚本,项目教程(讲解有挂)-哔哩哔哩wpk德州局怎么...
解密透视!wepoker养号规... 解密透视!wepoker养号规律,微乐南昌辅助神器,资料教程(有挂秘籍)-哔哩哔哩运wepoker养...
详细透视!wepoker国外版... 详细透视!wepoker国外版透视,微信微乐辅助ios,大纲教程(有挂神器)-哔哩哔哩1、wepok...
必备透视!大菠萝辅助器,微乐小... 必备透视!大菠萝辅助器,微乐小程序礼包码,烘培教程(有挂解密)-哔哩哔哩1、实时大菠萝辅助器透视辅助...
关于透视!拱趴大菠萝开挂方法,... 关于透视!拱趴大菠萝开挂方法,微信小程序游戏破解微乐辅助,举措教程(真的有挂)-哔哩哔哩1、完成拱趴...
普及透视!wepoker插件程... 普及透视!wepoker插件程序激活码,微乐麻将自建房app,策略教程(有挂技术)-哔哩哔哩wepo...
必备透视!德州私人局脚本,微乐... 必备透视!德州私人局脚本,微乐自建房辅助工具在哪,教程书教程(的确有挂)-哔哩哔哩1、首先打开德州私...
必备透视!aapoker发牌逻... 必备透视!aapoker发牌逻辑,微乐科技软件下载,妙招教程(有挂规律)-哔哩哔哩aapoker发牌...
了解透视!wepoker怎么破... 了解透视!wepoker怎么破解游戏,微乐自建房脚本使用安全吗,机巧教程(有挂分享)-哔哩哔哩运we...