본문 바로가기

Student/모여서 각자 코딩

19년도 여름방학 모각코 3일차 회고 0704

목표 angular 컴포넌트간의 변수 바인딩

변화감지


angular는 기본적으로 zone.js라는 변화 감지하는 라이브러리를 포함하고있다.

zonejs는 angular에서 만든 변화감지 라이브러리인데 범용적으로 사용하기 위해서

zonejs로 개발하였다. 기본적으로 angular는 프로그램 실행 동안에 view에 보이는 변수값이 변하면

zone이 이것을 감지해서 view도 변하게 만들어준다.

...더보기

사실 Angular는 양방향 바인딩을 지원하지 않는다. 양방향 바인딩을 위한 템플릿 문법[()](이것을 Banana in a box라고 부른다)에서 추측할 수 있듯이 양방향 바인딩은 이벤트 바인딩과 프로퍼티 바인딩의 축약 표현(Shorthand syntax)일 뿐이다. 즉, 양방향 바인딩의 실제 동작은 이벤트 바인딩과 프로퍼티 바인딩의 조합으로 이루어진다.

 

컴포넌트 간의 변수 바인딩


angular는 변수바인딩 방법이 2가지가 있다.

부모와 자식 컴포넌트 간의 바인딩observable을 이용한 바인딩이 있습니다.

#부모와 자식 컴포넌트 간의 바인딩

@input과 @output 어노테이션을 이용한다.

 

부모에서 자식으로 변수 값을 주는 경우에는

자식의 selector를 template에 적용할때 [자식 변수명]= "변수 값 또는 부모의 변수"으로 넘겨준다.

//부모 컴포넌트
import { Component } from '@angular/core';
@Component({
    selector: 'high-selector',
    template: `<low-selector [path]="./desktop/fileNm" //자식컴포넌트 
                   [title]="angular">
               </low-selector>`
})
export class HighComponent{
}
//자식 컴포넌트
import { Component } from '@angular/core';
@Component({
    selector: 'low-selector',
    template: `<img src="{{path}}" name="{{title}}">
               </img>`
})
export class LowComponent{
    @Input() path = "경로"; //상위 컴포넌트에서 path를 주지 않으면
                           //"경로"가 된다. (기본 속성값)
    @Input() title;
}

@input을 이용해서 값을 받는다.

 

 

이번엔 자식 컴포넌트가 부모 컴포넌트에게 값을 전달 하는 경우에는

//자식컴포넌트 
import { Component } from '@angular/core';
@Component({
    selector: 'low-selector',
    template: `<button (click)="onClick()">상위 컴포넌트에게 정보 전달
               </button>`
})
export class LowComponent{
    @Output() sendObject = new EventEmitter<Object>();

    data = {
        name: 'angular'
        ,email: 'naver@naver.com'
    }
    onClick(){
        this.sendObject.emit(data);
    }
}
//부모컴포넌트
import { Component } from '@angular/core';
@Component({
    selector: 'high-selector',
    template: `<low-selector (sendObject)="onRecvFunc($event)">
                     <span>{{name}}<span>
               </low-selector>`
})
export class HighComponent{
    name="name1"
    onRecvFunc(obj){
        name = obj.name;
    }

버튼 태그를 이용하고 이벤트로서 자식 컴포넌트에서 @output 어노테이션으로 값을 바인딩합니다.
값이 변했을 때 이벤트를 일으키기 위해서 EventEmitter를 사용해 주어야 한다.

 

#observable을 이용한 변수 값 바인딩

변수값을 넘기려는 것이 부모 자식간이 아니라면
observable을 이용한 변수 바인딩이 좋은 방법이다.

//service로 구현해 둔다. 
export class GlobalService {
    private subject = new Subject<any>();

    sendMessage(message: string) {
        this.subject.next(message);
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}
// 변수 값을 보내는 경우
export class SendComponent {
    constructor(private globalService: GlobalService) {}

    sendMessage() {
        this.globalService.sendMessage('메세지');    }
}
//변수 값을 받는 컴포넌트
export class ReceiveComponent implements OnDestroy {
    message: any;
    subscription: Subscription;

    constructor(private globalService: GlobalService) {

        this.subscription = this.globalService.getMessage().subscribe(message => { this.message = message; });    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

값이 변할 때 globalService의 '메세지' 값으로 메세지를 보내고
받는 컴포넌트에서 메세지가 오면 처리해주는 식으로 하면 바인딩이 된다.