通过routerLink导航时组件重新初始化

时间:2019-01-30 13:16:16

标签: html angular typescript angular6

我正在使用routerLink从Home Component导航到Result Component,但是每次我导航回某个组件时,这些组件都会重新初始化。

如何防止组件重新初始化?

下面是代码段

AppComponent HTML

<div class="collapse navbar-collapse">
  <ul class="nav navbar-nav">
    <li routerLinkActive="active" class="nav-item">
      <a class="nav-link" routerLink="/home">Home </a>
    </li>
    <li routerLinkActive="active"  class="nav-item">
      <a class="nav-link" routerLink="/results">Results</a>
    </li>
  </ul>
</div>

AppRoutingModule

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ResultComponent } from './pages/result/result.component';
import { HomeComponent } from './pages/home/home.component';

const routes: Routes = [
  {path: '', redirectTo: '/home', pathMatch: 'full'},
  {path:"results", component: ResultComponent},
  {path:"home", component: HomeComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {

}

ResultComponent

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-result',
  templateUrl: './result.component.html',
  styleUrls: ['./result.component.css']
})
export class ResultComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    console.log("created");
  }

}

当我从Home Component导航到Result Component时,它总是打印出“ created”。

这是预期的行为吗?

我的实际代码中添加了更多内容。

1 个答案:

答案 0 :(得分:0)

这正是角度的工作原理。