깜놀하는 해므찌로

Angular [()] / 양방향 바인딩 본문

IT

Angular [()] / 양방향 바인딩

agnusdei1207 2023. 4. 24. 13:53
반응형
SMALL

 

[] 프로퍼티 바인딩 문법
() 이벤트 바인딩 문법

두 개가 결합된 형태 [()]

<app-sizer [(size)]="fontSizePx"></app-sizer>
export class SizerComponent {

  @Input()  size!: number | string; // 현재 컴포넌트 안으로 들어오는 데이터
  @Output() sizeChange = new EventEmitter<number>(); // 부모 컴포넌트로 데이터를 보내기 위해
  dec() { this.resize(-1); }
  inc() { this.resize(+1); }

  resize(delta: number) {
    this.size = Math.min(40, Math.max(8, +this.size + delta));
    this.sizeChange.emit(this.size);
  }
}

1. Math.min() 함수는 주어진 숫자들 중 가장 작은 값을 반환

2. Math.max() 함수는 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환

 

 

 

/** AppComponent */

fontSizePx = 16;

3. 앱 컴포넌트 fontSizePx 프로퍼티 초기화

 

 

 

 

 

<!-- sizerComponent 템플릿 --> 

<div>
  <button type="button" (click)="dec()" title="smaller">-</button>
  <button type="button" (click)="inc()" title="bigger">+</button>
  <span [style.font-size.px]="size">FontSize: {{size}}px</span>
</div>
<!-- appComponent 템플릿 -->

<app-sizer [(size)]="fontSizePx"></app-sizer>
<div [style.font-size.px]="fontSizePx">Resizable Text</div>

4. 이제 버튼을 클릭하면 AppComponent.fontSizePx 프로퍼티 값이 갱신됩니다. 그러면 변경된 프로퍼티 값에 따라 스타일이 바인딩되기 때문에 화면에 표시된 글자도 커지거나 작아집니다.

 

 

 

 

<!-- /app.component.html (expanded) -->
<!-- 바인딩 문법과 이벤트 바인딩 문법을 짧게 줄여놓은 것 -->
<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>

5. $event 변수에는 SizerComponent.sizeChange 이벤트로 보낸 데이터가 담겨 있습니다. 이 변수의 값은 AppComponent.fontSizePx에 할당됩니다.

 

반응형
LIST