오늘은 컴포넌트를 만들어볼 건데요~
전에 봤던 <app-root></app-root> 이놈과 같은 걸 직접 만들어 보려 합니다.
app.component.html 의 내용을 간단하게 아래와 같이 바꿀게요.
<h1>this is AppComponent!</h1>
상품정보를 출력하고 싶다고 가정해봅시다.
일반적으로 app 폴더안에 하위 폴더로 생성합니다. app 폴더 안에 product 폴더를 만들어주세요.
그리고 product 폴더에 ts 파일과 html 파일을 만들겠습니다.
product.component.ts
// 아래의 @component 데코레이터를 사용하기 위한 import
import { Component } from '@angular/core';
// @component 데코레이터 사용
@Component({
selector: 'app-product',
templateUrl: './product.component.html'
})
export class ProductComponent {
// export 하여 다른 곳에서 import 할수 있도록 함
}
product.component.html
<p>I'm Product Component!</p>
다 된것 같으니 app.component.html 에 위에 selector로 지정해준 <app-product></app-product> 아래와 같이 추가해주면...
<h1>this is AppComponent!</h1>
<hr>
<app-product></app-product>
오류가 뜨네요...
app-product 를 모른다고 하네요. 네. 만들기만 하면 angular가 모릅니다. 알려줘야 합니다!
app.module.ts 을 살짝 보면 declarations 에 AppComponent 가 있습니다.
아하 이것 때문에 AppComponent의 selector 인 app-root를 제대로 인식할 수 있었던 겁니다! 그럼 우리가 만든 ProductComponent 도 추가해주면 되겠네요!
export 했던 ProductComponent 클래스를 이곳에서 import 하고 declarations 에 ProductComponent 를 추가합니다.
...
import { ProductComponent } from './product/product.component';
@NgModule({
declarations: [
...,
ProductComponent
],
...
})
export class AppModule { }
결과는...? 두둥
그런데 뭐 어렵지는 않지만 귀찮지 않나요?! 다음 명령어를 치면 그 고민이 말끔하게 해결됩니다. 바로
ng generate component 줄여서 ng g c !! ng g c products 명령을 해보겠습니다.
그럼 폴더와 파일들이 알아서 생성되고 app.module.ts 에도 자동으로 추가해줍니다! 와우 편리해라~
products.component.html
<app-product></app-product>
<app-product></app-product>
app.component.html
<h1>this is AppComponent!</h1>
<hr>
<app-products></app-products> <!-- app-products로 수정 -->
간단하게 명령만 치면 번거로운 작업없이 다음과 같이 쉽게 component를 만들 수 있습니다.
이상 새로 컴포넌트를 생성해보았습니다.
'choco's log > Angular' 카테고리의 다른 글
(6) 컴포넌트 템플릿, 스타일, 셀렉터 수정하기 (0) | 2019.11.13 |
---|---|
(4) Angular 프로젝트에 bootstrap 적용 (0) | 2019.09.25 |
(3) ngModel 사용해보기 (0) | 2019.09.24 |
(2) 앵귤러 앱 첫 편집 (0) | 2019.09.23 |
(1) Angular 시작 (0) | 2019.09.04 |