Search results for 'angular create component'

Angular 새로 Component 만들기

2017. 12. 11. 22:33

Angular에 대해서 대략 훑어 본 것 같으니 이제 직접 코딩을 해보도록 하겠습니다.

지난 글에서 말씀드렸듯이 Component들을 추가하여 Application을 만들어갑니다.

바로 그 Component를 추가하는 2가지 방법에 대해서 공부해볼게요.


1. Angular CLI(Command-Line-Interface)

ng generate component (축약: ng g c) 라는 CLI명령어를 이용할 수 있습니다.

만약 budget이라는 컴포넌트를 만들고 싶다면 아래와 같이 사용합니다.

ng generate component budget (축약: ng g c budget)

이렇게 명령어를 입력하면 directory와 파일이 생성됩니다.

app.module.ts에 필요한 코드가 자동으로 추가되구요.

angular-cli (create component command)


2. Manual

물론 명령어를 사용하는 것은 편하고 좋은 방법입니다.

하지만 더 깊은 이해를 위해 하나,하나 손으로 만들어 보는 것도 좋겠죠?

새로운 Component를 추가하려면 당연히 먼저 파일을 만들어야합니다.

Component는 ts, html, css 3가지 파일로 이루어지게 됩니다.

일단 간단하게 Component당 하나의 폴더를 만드는 것으로 가정하죠.

(CLI를 사용하는 것과 동일하게 폴더 구조를 만들겠습니다.)

budget폴더를 생성하고 그 안에 3개의 파일을 생성합니다.


budget

- budget.component.html

- budget.component.css

- budget.component.ts


먼저 ts파일을 구성해보죠.

Angular의 Component를 사용하기 위해 import를 먼저 합니다.

import { Component } from '@angular/core';

지난 글의 @Component라는 Metadata를 넣어줍니다.

@Component 안에는 selector, templateUrl, styleUrls이 필요합니다.

selector는 templateUrl이 위차할 html 태그 이름이라고 보시면 됩니다.

자동 생성되는 규칙대로 'app-budget'이라고 넣어주겠습니다.

templateUrl은 새로 만든 html 파일 이름을 넣구요.

styleUrls는 array입니다. [ ]안에 생성해준 css파일 이름을 하나 넣겠습니다.

위 세가지를 구성해주고, class를 선언하면 ts 파일 구성이 완료됩니다.

@Component({
  selector: 'app-budget',
  templateUrl: './budget.component.html',
  styleUrls: ['./budget.component.css']
})

위와 같이 구성해준다음 이 Component를 볼 수 있도록 노출시켜줍니다.

export class BudgetComponent{}

TypeScript에서 객체를 다른 객체에서 import하여 사용할 수 있도록 하는 문법입니다.

TypeScript에 대해서는 자세히 다루지 않을게요.

저도 자세히 알지는 못하고 Angular에서 쓸 때 필요한 만큼만 익혀 가고 있습니다.


css 파일은 그냥 두고(꾸미기는 생략!) html 파일을 편집해봅시다.

<h3>I made first component!!!</h3>


마지막으로 이 Component를 사용하겠다는 것을 Angular에 알려야합니다.

app.module.ts에 import하고 @NgModule의 declaration에 추가합니다.

NgModule에 대해서는 추후에 더 자세히 다루도록 하겠습니다.

import { BudgetComponent } from '@./budget/buget.component';

@NgModule({
  declaration: [
    BudgteComponent,
    ...
  ], 
  ...
})


위 두 가지 방법을 통해 새로운 컴포넌트를 추가할 수 있습니다.

그리고 그 컴포넌트를 화면에 출력해봅시다.

app.component.html에 우리가 지정한 selector (app-budget) 태그를 넣습니다.

<div style="text-align:center">
  <app-budget></app-budget>
</div>

ng serve를 통해 화면을 실행하면 아래와 같은 화면이 뜹니다.


새로운 Component가 추가된 angular 첫 페이지


TechTrip IT Tech/Angular