Angular Add Component
1. 수동으로 Component 생성
사진1) manul 폴더및 파일생성 |
// src/app/manual/manual.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-manual', // component명칭을 작성한다.
templateUrl: './manual.component.html', // 해당 component가 사용할 html 템플릿 주소를 입력한다.
})
export class ManualComponent {}
코드1) ts파일 작성
<!-- src/app/manual/manual.component.html -->
<h1>This component was build by manual!</h1>
코드2) html파일 작성
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ManualComponent } from './manual/manual.component';
@NgModule({
declarations: [AppComponent, ManualComponent], // declarations에 components class를 추가한다.
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
코드3) 앱 모듈에 추가
<!-- src/app/app.component.html -->
<!-- 작성한 selector(app-manual)를 tag로 입력한다. -->
<app-manual></app-manual>
코드4) manual 컴포넌트 추가
사진2) 수동 컴포넌트 출력 |
- angular cli를 이용하여 component를 생성한다. (node v18.18.0)
- angular가 글로벌로 설치되어 있으면 npx @angular/cli@16.2.3을 ng로 변경할수 있다.
$ npx @angular/cli@16.2.3 generate component
사진3) cli로 component생성 |
사진4) cli폴더 자동 생성 |
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ManualComponent } from './manual/manual.component';
import { CliComponent } from './cli/cli.component';
@NgModule({
declarations: [AppComponent, ManualComponent, CliComponent], // declarations에 components class를 추가한다.
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
코드5) 자동 컴포넌트 삽입
<!-- src/app/app.component.html -->
<!-- 작성한 selector(app-manual)를 tag로 입력한다. -->
<app-manual></app-manual>
<!-- 자동으로 생성된 component의 selector(app-cli)를 tag로 입력한다. -->
<app-cli></app-cli>
코드6) app 컴포넌트에 cli컴포넌트 추가
사진5) 추가한 cli컴포넌트 결과 |
GitHub : https://github.com/Alex-Choi0/angular_create_component_example.git
댓글
댓글 쓰기