5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

同じURLにルーティングする際にngOnInitを呼び出すようにする

Posted at

Angularで同じURLにルーティングするとngOnInitメソッドは呼び出されない

app-routing.module.ts

const routes: Routes = [
  { path: 'sample', component: SampleComponent }
};

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

sample.component.ts

@Component({
 selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.css']
})
export class SampleComponent implements OnInit {
  constructor(private router:Router) {}

  //2回目以降は呼び出されない
  ngOnInit(): void {
  }

  //自分自身へ遷移する
  click(event:any) :void {
  //同じURLへ遷移
    this.router.navigate(['/sample']);
  }
}

これだと同じURLへ遷移して同一画面上の値を更新しようとしても更新されない。
この場合はapp-routing.module.tsとsample.component.tsを以下のように変更する

app-routing.module.ts

const routes: Routes = [
  { path: 'sample', component: SampleComponent }
};

@NgModule({
  //同じURLのときはreloadするように指定
  imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

sample.component.ts

@Component({
 selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.css']
})
export class SampleComponent implements OnInit {
  constructor(private router:Router) {
    //shouldReuseRouteをfalseに設定
    this.router.routeReuseStrategy.shouldReuseRoute = function () {
      return false;
    };
  }

  //2回目も呼び出される
  ngOnInit(): void {
  }

  //自分自身へ遷移する
  click(event:any) :void {
  //同じURLへ遷移
    this.router.navigate(['/sample']);
  }
}

※もしかしたらshouldReuseRouteの設定だけでうまくいくかもしれないが、自分は上記で動作できた。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?