컴포넌트 데이터바인딩 하기 2

부모에서 선언한 변수를 자식 컴포넌트에서 사용하기

  1. 자식 컴포넌트를 생성 한다.
ng g c child 
  1. 부모 컴포넌트의 html 파일에 자식 컴포넌트 추가
<h1>{{ title }}</h1>

<app-child [item]="data"></app-child>
  1. 부모 컴포넌트의 ts 파일에서 자식컴포넌트에서 사용하기 위한 변수 추가(data)
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'ang-data';

  data = 10;
}
  1. 부모컴포넌트의 html 파일에서 ts에서 선언한 변수 입력
<h1>{{ title }}</h1>

<app-child [item]="data"></app-child>
  1. 4번을 적용 시키기위해서 자식 컴포넌트의 ts 파일에서 Input을 Import 해준다.
import { Component, OnInit, **Input** } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}
  1. Input() 적용하기
//  @Input() item=0 추가
import { Component, OnInit, **Input** } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {

  constructor() { }
 @Input() item=0 
  ngOnInit(): void {
  }

}