google에서 만든 Typescript기반 웹 프레임워크
설치
npm install -g @angular/cli
1) 프로젝트 생성
ng new my_tutorial
2) Heroes component 생성
ng generate component heroes
- 자동으로
app.module.ts
에HeroesComponent
가 선언됨- template에 selector를 통해 해당 컴포넌트 표현
# app/heroes/heroes.component.ts @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.css'] })ㅁ export class HeroesComponent implements OnInit { constructor() { } ngOnInit(): void { hero = 'Superman'; } }
# app.heroes.component.html <p>{{ hero }}</p>
# app/app.component.html <h1>{{ title }}</h1> <app-heroes></app-heroes>
ngModel
component의 프로퍼티 값과 Input 박스 값을 양방향 바인딩하는 문법
1) FormsModule 로드
ngModel
은 FormsModule 패키지가 제공# app.module.ts import { FormsModule } from '@angular/forms'; @NgModule({ ... imports: [ BrowserModule, AppRoutingModule, FormsModule ], ... }) ...
2) HeroesComponent 변경
# app.heroes.components.html <h2>{{ hero.name | uppercase }} Details</h2> <div><span>id: </span>{{ hero.id }}</div> <div><span>name: </span>{{ hero.name }}</div> <div> <label for="name">Hero name: </label> <input id="name" [(ngModel)]="hero.name" placeholder="name" /> </div>
# app.heroes.components.ts export class HeroesComponent implements OnInit { constructor() {} ngOnInit(): void {} hero: Hero = { id: 1, name: 'Windstorm', }; }
1) *ngFor
배열 형태의 프로퍼티를 템플릿에 표현하기 위한 문법
# app.heros.component.html <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes"> <button type="button"> <span class="badge">{{ hero.id }}</span> <span class="name">{{ hero.name }}</span> </button> </li> </ul>
# app.heroes.component.ts import { HEROES } from '../mock-heroes'; export class HeroesComponent implements OnInit { ... heroes = HEROES; }
2) *ngIf
조건부로 템플릿에 표현 가능한 문법
3) 클릭이벤트 바인딩
- 클릭 이벤트로 인해 selectedHero 값이 유효할 때만 표현
- 클릭된 영웅 버튼은 .selected 클래스 적용
# app.heroes.component.html <div *ngIf="selectedHero"> <h2>{{ selectedHero.name | uppercase }} Details</h2> <div>id: {{ selectedHero.id }}</div> <div> <label for="hero-name">Hero name: </label> <input id="hero-name" [(ngModel)]="selectedHero.name" placeholder="name" /> </div> </div> <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes"> <button type="button" (click)="onSelect(hero)" [class.selected]="hero === selectedHero"> <span class="badge">{{ hero.id }}</span> <span class="name">{{ hero.name }}</span> </button> </li> </ul>
# app.heroes.component.css .selected { color: #ffffff; background-color: #000000; }
# app.heroes.component.ts export class HeroesComponent implements OnInit { ... selectedHero?: Hero; onSelect(hero: Hero): void { this.selectedHero = hero; } }
https://github.com/kimphysicsman/angular_my_tutorial