[Angular] Component Interaction = 부모 자식 데이터 전달



1. parent -> child 데이터 전달

parent .ts

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent {
title = 'Angular-app';
public name ='voomin public';
}


parent .html

<app-test [parentData]='name'></app-test>

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

@Component({
selector: 'app-test',
template: `
<h2>{{"Hello "+name}}</h2>
`,
styles: []
})
export class TestComponent implements OnInit {
@Input('parentData') public name;

constructor() { }

ngOnInit() {

}
}






2. child -> parent 데이터 전달

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

@Component({
selector: 'app-test',
template: `
<h2>{{"Hello "+name}}</h2>
<button (click)='fireEvent()'>Send Event</button>
`,
styles: []
})
export class TestComponent implements OnInit {
@Input('parentData') public name;
@Output()public childEvent = new EventEmitter();

constructor() { }

ngOnInit() {

}
fireEvent(){
this.childEvent.emit('Hey voomin kim');
}
}

parent .ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent {
title = 'Angular-app';
public name ='voomin public';
public message = "";
}

parent .html
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
{{message}}
</h1>
</div>

<app-test (childEvent)='message=$event' [parentData]='name'></app-test>

결과


--- Send Event 클릭 후 click()








출처 : https://youtu.be/BGy8DdGw_WE

댓글

가장 많이 본 글