简体   繁体   English

Angular 5-关于ngOnInit事件的RouterLink

[英]Angular 5 - RouterLink on ngOnInit event

When I click on this button it goes to a certain page: 当我单击此按钮时,它会转到某个页面:

<button routerLink="/mypage">Click Here</button>

What I want to do it to add this to add it to the ngOnInit: 我要添加的内容将其添加到ngOnInit中:

 ngOnInit() {
  // Code to do the same as routerLink here
}

Can this be done? 能做到吗? If so how? 如果可以,怎么办?

Simple as hello 简单如你好

import { Router } from '@angular/router';

constructor(private router: Router) {}
ngOnInit() { this.router.navigate('/mypage'); }

Although I advise you to use this notation instead : 尽管我建议您改用以下符号:

ngOnInit() { this.router.navigate(['/mypage']); }

The array notation is more flexible than the string one. 数组表示法比字符串表示法更灵活。

You need to import Router : 您需要导入Router:

import { Router } from '@angular/router';

constructor(private router: Router){}

ngOnInit() {
  // Code to do the same as routerLink here
  this.router.nvaigate(['/mypage']);
}

Use router.navigate 使用router.navigate

this.router.nvaigate('mypage')

Make sure you have imported 确保您已导入

import { Router } from '@angular/router';

If I understood you correctly you want to go to the certain route when one component loads it's OnInit. 如果我对您的理解正确,那么当一个组件加载OnInit时,您要转到特定路径。

constructor(private: Router) { }
ngOnInit() {
  this.router.navigate(['/mypage']);
}

You can write this, but make sure you have RouterModule imported in the module where this component will be used. 您可以编写此代码,但请确保在要使用此组件的模块中导入了RouterModule。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM