Tour of Heroes 예제 따라하기
※ Angular에서 Router는 사용자가 요청한 URL을 해석하고 출력을 담당하는 컴포넌트와 연결하는 열할을 한다.
- Template 파일의 <router-outlet></router-outlet> 영역에 출력이 된다.
1. Application에 Router모듈을 생성한다.
- ng generate module app-routing --flat --module=app 명령어로 생성
- Console출력에서 생성된 파일과 수정된 파일을 확인
2. router module Class를 수정해서 Application에서 사용할 수 있도록 export
- src/app/app-routing.module.ts 파일을 수정
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; @NgModule({ exports: [ RouterModule] }) export class AppRoutingModule { }
3. routes 추가하기
- Route에는 두가지 속성값이 있는데 path와 component가 있는데
- path : 주소창에 보여지는 문자
- component : 해당 주소가 호출되었을때 보여질 component
- src/app/app-routing.module.ts 파일을 수정
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HeroesComponent } from './heroes/heroes.component'; const routes: Routes = [ { path: 'heroes', component: HeroesComponent } ]; @NgModule({ exports: [ RouterModule] }) export class AppRoutingModule { }
4. Router를 초기화
- Router를 초기화 하고 브라우져 주소창 변화를 감지하기 위해 RouterModule.forRoot 추가
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HeroesComponent } from './heroes/heroes.component'; const routes: Routes = [ { path: 'heroes', component: HeroesComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule] }) export class AppRoutingModule { }
5. RouterOutlet을 정의해서 출력부분을 지정한다.
- src/app/app.component.html 파일 수정
{{title}}
6. routerLink를 사용하여 화면 링크 구성
- src/app/app.component.html 파일 수정
{{title}}
- 브라우져에서 확인하면 초기화면에는 hero목록이 사라졌고 링크만 나오는데 링크를 클릭시 hero목록이 표시됨
7. DashBoard View를 생성한다.
- ng generate component dashboard 명령어로 생성 후 Console확인
8. dashboard 컴포넌트의 Template 파일을 수정
- src/app/dashboard/dashboard.component.html
Top Heroes
9. dashboard component class 파일을 수정
- src/app/dashboard/dashboard.compont.ts
import { Component, OnInit } from '@angular/core'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: [ './dashboard.component.css' ] }) export class DashboardComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) { } ngOnInit() { this.getHeroes(); } getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes.slice(1, 5)); } }
10. dashboard component의 style파일 수정
- src/app/dashboard/dashboard.component.css
/* DashboardComponent's private CSS styles */ [class*='col-'] { float: left; padding-right: 20px; padding-bottom: 20px; } [class*='col-']:last-of-type { padding-right: 0; } a { text-decoration: none; } *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } h3 { text-align: center; margin-bottom: 0; } h4 { position: relative; } .grid { margin: 0; } .col-1-4 { width: 25%; } .module { padding: 20px; text-align: center; color: #eee; max-height: 120px; min-width: 120px; background-color: #607D8B; border-radius: 2px; } .module:hover { background-color: #EEE; cursor: pointer; color: #607d8b; } .grid-pad { padding: 10px 0; } .grid-pad > [class*='col-']:last-of-type { padding-right: 20px; } @media (max-width: 600px) { .module { font-size: 10px; max-height: 75px; } } @media (max-width: 1024px) { .grid { margin: 0; } .module { min-width: 60px; } }
11. 기본 route 및 dashboard route등록
- src/app/app-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HeroesComponent } from './heroes/heroes.component'; import { DashboardComponent } from './dashboard/dashboard.component'; const routes: Routes = [ {path : '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'heroes', component: HeroesComponent }, { path: 'dashboard', component: DashboardComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule] }) export class AppRoutingModule { }
12. 현재까지 작업된 결과를 확인
- http://localhost:4200 으로 접속시 주소는 자동으로 http://localhost:4200/dashboard 로 redirect되며 아래와 같은 화면이 보여진다.
13. 화면간 이동을 위해 dashboard 링크를 생성
- src/app/app.component.html
- 수정후 브라우져에서 dashboard와 heroes 화면 이동을 확인
{{title}}
14. hero component에서 hero내용을 수정하는 부분을 herodetail component에서 보여주기 위해 Template파일 수정
- src/app/heroes/heroes.component.html 출력부분 삭제
My Heroes
- {{hero.id}} {{hero.name}}
15. 상세보기에 대한 route 등록
- src/app/app-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HeroesComponent } from './heroes/heroes.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { HeroDetailComponent } from './hero-detail/hero-detail.component'; const routes: Routes = [ {path : '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'heroes', component: HeroesComponent }, { path: 'detail/:id', component: HeroDetailComponent}, { path: 'dashboard', component: DashboardComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule] }) export class AppRoutingModule { }
17. dashboard component에서 hero detail로 routerLink 생성
- src/app/dashboard/dashboard.component.html
Top Heroes
18. heroes list에서 작동방식을 onSelect 호출에서 routerLink방식으로 변경
- src/app/heroes/heroes.component.html
19. heroes component 에서 불필요 코드 삭제
- src/app/heroes/heroes.component.ts 파일에서 아래 부분만 필요
import { Component, OnInit } from '@angular/core'; import { Hero } from '../hero'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.css'] }) export class HeroesComponent implements OnInit { heroes: Hero[]; constructor(private heroService: HeroService) { } ngOnInit() { this.getHeroes(); } getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } }
20. HeroDetail component를 route형식으로 변경
- src/app/hero-detail/hero-detail.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { Hero } from '../hero'; import { ActivedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.css'] }) export class HeroDetailComponent implements OnInit { @Input() hero: Hero; constructor( private route: ActivedRoute, private heroService: HeroService, private location: Location ) { } ngOnInit(): void { this.getHero(); } getHero(): void { const id = +this.route.snapshot.paramMap.get('id'); this.heroService.getHero(id) .subscribe(hero => this.hero = hero); } goBack(): void { this.location.back(); } }
21. HeroService에 gtHero() 메소드를 추가
- src/app/hero.service.ts 파일에 추가
getHero(id: number): Observable{ // Todo: send the message _after_ fetching the hero this.messageService.add(`HeroService: fetched hero id=${id}`); return of(HEROES.find(hero => hero.id === id)); }
22. 뒤로가기 버튼 추가
- src/app/hero-detail/hero-detail.component.html 파일에 추가
- src/app/hero-detail.component.ts 파일에 추가{{ hero.name | uppercase }} Details
id: {{hero.id}}
import { Component, OnInit, Input } from '@angular/core'; import { Hero } from '../hero'; import { ActivedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.css'] }) export class HeroDetailComponent implements OnInit { @Input() hero: Hero; constructor( private route: ActivedRoute, private heroService: HeroService, private location: Location ) { } ngOnInit(): void { this.getHero(); } getHero(): void { const id = +this.route.snapshot.paramMap.get('id'); this.heroService.getHero(id) .subscribe(hero => this.hero = hero); } goBack(): void { this.location.back(); } }
'개발 > Front-End' 카테고리의 다른 글
[Angular4] Tour of Heroes 예제 따라하기 5 (0) | 2018.03.24 |
---|---|
[Angular4] Tour of Heroes 예제 따라하기 4 (0) | 2018.03.19 |
[Angular4] Tour of Heroes 예제 따라하기 3 (1) | 2018.03.17 |
[Angular4] Tour of Heroes 예제 따라하기 2 (0) | 2018.03.15 |
[Angular4] Tour of Heroes 예제 따라하기 1 (0) | 2018.03.13 |