히어로들의 여행 : 5. 네비게이션 추가하기

Sang heon lee·2022년 9월 1일
0

히어로들의 여행

목록 보기
5/6

라우팅 영역(RouterOutlet)추가하기

  • <router-outlet>은 라우팅 된 화면이 표시될 위치를 지정하는 엘리먼트입니다.
// src/app/app.component.html

<h1>{{ title }}</h1>
<nav>
  <a routerLink="/dashboard">Dashboard</a>
  <a routerLink="/heroes">Heroes</a>
</nav>
<router-outlet></router-outlet>
<app-messages></app-messages>
// src/app/app.component.html

<h1>{{ title }}</h1>
<nav>
  <a routerLink="/dashboard">Dashboard</a>
  <a routerLink="/heroes">Heroes</a>
</nav>
<router-outlet></router-outlet>
<app-messages></app-messages>

이전화면으로 돌아가기 (location)

// src/app/component/hero-detail/hero-detail.component.html

<div *ngIf="hero">
  <h2>{{ hero.name | uppercase }} Details</h2>
  <div><span>id: </span>{{ hero.id }}</div>
  <div>
    <label for="hero-name">Hero name: </label>
    <input id="hero-name" [(ngModel)]="hero.name" placeholder="name" />
  </div>
  <button (click)="goBack()">go back</button>
</div>
// src/app/component/hero-detail/hero-detail.component.ts

import { Location } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HSModel } from 'src/app/model';
import { HeroService } from 'src/app/service/hero.service';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.scss'],
})
export class HeroDetailComponent implements OnInit {
  @Input() hero?: HSModel.Hero;

  constructor(
    private activatedRoute: ActivatedRoute,
    private heroSerive: HeroService,
    private location: Location
  ) {}

  ngOnInit(): void {
    this.getHero();
  }

  getHero(): void {
    const id = Number(this.activatedRoute.snapshot.paramMap.get('id'));
    this.heroSerive.getHero(id).subscribe((hero) => (this.hero = hero));
  }

  goBack(): void {
    this.location.back();
  }
}
profile
개초보

0개의 댓글