본문 바로가기

Tech/Angular

[Angular] 컴포넌트 생성 및 클래스 정의하기

반응형

이미지 출처 : Pixabay

지난 글에서 Angular 개발환경을 맥 상에 구축했습니다.

이번 글에서는 컴포넌트를 생성하고 클래스를 정의해 준 다음 이를 뷰에 띄워보겠습니다.

Reference : https://angular.io/tutorial/toh-pt1

 

Angular

 

angular.io

 

터미널 상에서 다음 명령어를 입력합니다.

ng generate component employees

ng generate component employees

그리고 Employee 컴포넌트에서 보여주게 될 클래스를 src/app/employees 경로 상에 작성해줍니다.

// employee.ts

export class Employee {
  id: number;
  name: string;
}

 

작성한 클래스를 employees.component.ts 내에서 import한 후, employee 하나를 임의로 생성해 줍니다.

// employee.component.ts

import { Component, OnInit } from '@angular/core';
import { Employee } from './employee';

@Component({
  selector: 'app-employees',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {
  employee: Employee = {
    id : 1,
    name : 'Sean'
  };

  constructor() { }

  ngOnInit() {
  }

}

 

이렇게 정의해 준 Employee를 페이지 상에서 보여주기 위해 html 파일을 작성합니다.

<!-- employee.component.html -->

<div><span>id: </span>{{employee.id}}</div>
<div><span>name: </span>{{employee.name}}</div>

 

그리고 이렇게 만들어 준 employees 컴포넌트 뷰를 보여주기 위해 app.component.html을 수정해 줍니다.

<!-- app.component.html -->

<h1> {{title}} </h1>
<app-employees></app-employees>

만일 컴포넌트명을 employees가 아닌 다른것으로 생성했다면 해당 컴포넌트명.component.ts 상의 selector 이름을 참조하면 됩니다.

****.component.ts 상의 selector 가져오기

여기까지 마무리되었다면 실행 결과는 다음과 같습니다.

localhost:4200

본 샘플 프로젝트는 git에서 확인할 수 있습니다 : https://gitlab.com/Sean_Ma/angularSampleProject

반응형