자식에게 데이터를 받아서 startTime함수를 호출해 아래처럼 데이터를 받았다.
<div class = 'title'>
<div class = 'display'>
<app-time-display></app-time-display>
<app-buttons (clickEvent)='startTime($event)'></app-buttons>
</div>
</div>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-section',
templateUrl: './section.component.html',
styleUrls: ['./section.component.scss']
})
export class SectionComponent implements OnInit {
present='welcome';
constructor() { }
startTime(childData){
this.present=childData;
}
ngOnInit(): void {
}
}
============================================
받은 데이터를 자식에게 전달해보자.
일단 present변수에 값이 있으니 부모 html에서 이렇게 해준다.
<div class = 'title'>
<div class = 'display'>
<app-time-display [inputData]='present'></app-time-display>
<app-buttons (clickEvent)='startTime($event)'></app-buttons>
</div>
</div>
inputData라는 변수에 present를 받는다는 의미.
그럼 inputData를 만들러 가자.(자식에서)
inputData를 만드는데 줄때는 @Output을 하였고,
지금은 받는것이니 @Input()을 사용한다.(데코레이터)
그럼 시작 버튼(데이터를 처음에 준 자식에 있는 버튼)을 클릭하지 않을때가 첫페이지 이므로,
ngOnChanges함수엔 welcome이 들어가있을 것이다.(present 초기값)
여기서 ngOnChanges 는 Input데이터가 바뀔때마다 작동하는것임.
그리고 버튼을 누르면 welcome에서 change!로 바뀐다.
다시 누르면 어차피 change!니까 ngOnChanges 함수는 호출이 되지 않는다.
import { Component, Input, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-time-display',
templateUrl: './time-display.component.html',
styleUrls: ['./time-display.component.scss']
})
export class TimeDisplayComponent implements OnInit {
@Input()
inputData:string;
test=0;
constructor() {
setInterval(() => {
this.test++;
}, 1000)
}
ngOnChanges(changes: SimpleChanges){
console.log(changes);
}
ngOnInit(): void {
}
}
'Developer' 카테고리의 다른 글
[Angular]module? (0) | 2020.10.03 |
---|---|
[Angular]export해서 import 하는법 (2) | 2020.10.03 |
[Angular]자식의 데이터를 부모에게 넘기기 (0) | 2020.10.03 |
[Angular]click 이벤트 바인딩 (0) | 2020.10.03 |
[typescript]타입가드 (0) | 2020.10.02 |