티스토리 뷰

데이터(클래스)와 뷰(템플릿)의 이야기

 

데이터가 바뀌면 뷰는 자동으로 바뀐다.

데이터를 바꾸려면 사용자의 입력이 필요하다.

사용자가 입력함과 동시에! 뷰를 바꾸려면 양방향 데이터바인딩을 사용한다.

 

부모 => 자식 뭔가를 주겠다고 명시적으로 적어야하고

바뀐거에대한 이벤트를 다시 주려면? => 이벤트를 또 가지고있어야하고

이것을 합친게 양방향 데이터바인딩

 

컴포넌트 트리상에 붙어있다면? => @Input Output

붙어있지않다면?

  • 같은 가지에 있다면?
  • 같은 가지가 아니라면?
    • 중개자
    • 서비스

템플릿과 데이터바인딩


데이터바인딩시,  앵귤러는 부모컴포넌트 => 자식컴포넌트로 내려줄때

 

부모컴포넌트 html 뷰

app.component.html

<div>
  {{ title }}
  <app-sample1></app-sample1>
  <app-sample2 test="title"></app-sample2>
</div>

 

자식컴포넌트는 트리로 구성이 되어있기에

@Input을 사용하여 클래스 컴포넌트안에

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

@Component({
  selector: 'app-sample2',
  templateUrl: './sample2.component.html',
  styleUrls: ['./sample2.component.css'],
})
export class Sample2Component implements OnInit {
  constructor() {}

  @Input() test: any;

  ngOnInit(): void {}
}

@Input을 사용하여 test라는 부모컴포넌트에 있는 데이터를 쓴다는것을 명시해준 후

나타낸다.

<p>{{ test }}</p>

 

 

결국 부모컴포넌트에서 리액트의 props식으로 값을 내려준것 이라고 생각하면 된다.

 

test='title'로 하면

문자열 그대로 들어가는 반면

변수를 사용하고싶으면

[test]='title' (프로퍼티바인딩)

변수 title값인 앵귤러 시작이 들어감

 


@Output을 사용하여 이제는 props끌어올리기 처럼 부모컴포넌트가 자식컴포넌트에 있는것을 사용함

 

부모에게 custom()함수를 만들어주고 

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = '앵귤러 시작!';
  names = ['이채영', '서예린', '박예진'];

  custom() {
    console.log('custom');
  }
}

 

html 뷰로 보여주는 부분을 보면

 

custom이란 함수가 실행될것이다. 그런데 안에들어있는 custom은 어떤 이벤트인가. 그것은 자식으로부터 받을것이다!

<div>
  {{ title }}
  <app-sample1></app-sample1>
  <app-sample2 [test]="title"></app-sample2>
  <app-sample2 *ngFor="let name of names" [test]="name"></app-sample2>
  <app-sample2 test="title" (custom)="custom()"></app-sample2>
</div>

 

자식에 @Output을 사용하여 올려준다.

 

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

@Component({
  selector: 'app-sample2',
  templateUrl: './sample2.component.html',
  styleUrls: ['./sample2.component.css'],
})
export class Sample2Component implements OnInit {
  constructor() {}

  @Input() test: any;
  @Output() custom = new EventEmitter();

  disabled = true;

  ngOnInit(): void {
    setTimeout(() => {
      this.disabled = false;
      this.custom.emit();
    }, 5000);
  }
}

custom = new EventEmitter()이고, => 요것은 앵귤러에서 지원하는 이벤트 기능? 내장되어있는 함수

 

this.custom.emit();을 사용하여 실행시킨다. 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함