Angular

[앵귤러] 컴포넌트 사용하기

반응형

[앵귤러] 컴포넌트 사용하기


컴포넌트 생성

ng g c 컴포넌트명

이렇게 생성하면 ts, html, css, spec.ts 총 4가지가 만들어짐

만약 ts만 만들고 싶다면?

ng g c 컴포넌트명 -it -is -spec false

양방향 바인딩 [(ngModel)]을 사용할 때는 app.module.ts에 다가 import 추가
import { FormsModule } from '@angular/forms';

 imports: [
    FormsModule
 ]

부모 컴포넌트에서 자식 컴포넌트로 데이터 보내기


클래스 안에 자식으로 보낼 데이터를 입력

msg = "i am a parent";

템플릿(html)에 불러오는 자식 컴포넌트의 selector안에 데이터를 입력

<app-child [name]="msg"></app-child>

이제 자식 컴포넌트에서 name이라는 이름으로 msg 데이터를 가져올 수 있음

부모 컴포넌트 코드

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

@Component({
  selector: 'app-parent',
  template: `
    <h1></h1>
    <app-child [name]="msg"></app-child>
  `,
  styles: []
})
export class ParentComponent implements OnInit {

  title = '부모 컴포넌트입니다';
  msg = "i am a parent";
  constructor() { }

  ngOnInit() {
  }

}

데이터를 불러오는 것은 input, 내보내는 것은 output. 지금은 input이 필요한 상황

import { Component, OnInit, Input } from '@angular/core';

input은 2가지 방법으로 입력 가능

  1. @Component({ }) 안에 inputs로 설정
@Component({
  selector: 'app-child',
  template: `
    <h3></h3>
    `,
  styles: [],
  inputs : ['name']
})
  1. 클래스 안에 Input 생성
export class ChildComponent implements OnInit {

	@Input() name: string;

}

자식 컴포넌트 템플릿(html)에 아래와 같이 입력하면 데이터를 불러올 수 있음

<h3></h3>

자식 컴포넌트에서 부모 컴포넌트로 값을 전달하기

반대의 경우에는 Output을 사용할 차례다.

@Output 장식자로 선언한 변수를 EventEmitter로 초기화, 부모로 보낼 시점에 emit() 메서드를 통해 부모로 이벤트 전달

자식 컴포넌트에서 import에 EventEmitter, Output 추가

import { Component, OnInit, EventEmitter, Output } from '@angular/core';

자식 컴포넌트 클래스에서 @Output으로 설정한 outputProperty 변수 선언

 @Output() outputProperty = new EventEmitter<boolean>();

자료형을 boolean으로 선언한 상황이다. (true, false)

이 자료형은 emit()으로 넘겨줄 때 사용하는 자료형. 따라서 받는 컴포넌트에서도 동일하게 선언해야 한다. 따라서 이벤트가 발생하면, emit() 메서드를 통해 부모 컴포넌트 값이 전달된다.

export class GrandsonComponent implements OnInit {
  active = false;

  @Output() outputProperty = new EventEmitter<boolean>();
  
  updateParent(active:boolean) {
    this.active = !active;
    this.outputProperty.emit(this.active);
  }
  
  constructor() { }

  ngOnInit() {
  }

}

자식 컴포넌트에서 템플릿(html)은 클래스에서 작성한 updateParent 함수를 통해 가져온다.

@Component({
  selector: 'app-grandson',
  template: `
    <div>손자
    <button (click)="updateParent(active)">부모에게 이벤트 보내기</button>
    </div>
  `,
  styles: []
})

이제 이를 받을 부모 컴포넌트의 템플릿에 작성해본다.

<app-grandson (outputProperty)="outputEvent($event)"><app-grandson>

동일한 속성명(outputProperty)를 통해 자식 컴포넌트가 전달한 값을 받는다.

반응형