on
Angular 컴포넌트에 데이터 보내기 (SET, ngOnChange())
Angular 컴포넌트에 데이터 보내기 (SET, ngOnChange())
P.S Angular를 처음 해보는 지라 잘못된 정보가 있을 수도 있습니다. 차차 수정해 나가겠습니다.
SET 사용해보기
studentsInfo.ts 에 학생 데이터가 있다. 데이터를 app 컴포넌트 통해 넣어 자식 컴포넌트에 받은 후 데이터를 보여줘본다.
studentsInfo.ts
app.component.ts에 학생 데이터를 불러옴
그후 부모로부터 데이터를 상속받을 컴포넌트 생성
서버가 실행 중인 경우 터미널을 하나 더 켠 후 ng g c 컴포넌트명 을 사용해 컴포넌트 추가.
다시 app.component.html로 돌아가 app.component.ts에 정의한 students를 불러옴.
*ngFor 은 for문과 같다. app.component.ts에서 studentsInfo 데이터를 students로 정의했고, students 배열 안에 데이터를 하나씩 빼오기 위해 for문을 돌린다.
컴포넌트에 데이터를 보내기 위해 [student]는 key로 ‘student’는 value가 된다.
set.component.ts로 가 app.component.html에서 보낸 [student]를 받기위해 @Input()을 사용한다.
@Input() set을 통해 [student]를 받는다. student의 타입은 String과 number 2가지가 있기 때문에 우선 any 타입으로 정의한다. 그리고 _student라고 student값을 받기위해 _student:any; 를 선언하고 This를 통해 값을 넣는다.
set.component.html로 가서 {{}}를 이용해 값을 불러온다.
확인
ngOnChange 사용해보기
버튼을 2개 만들고, 버튼을 누르면 컴포넌트에 들어가는 값이 바뀌면서(studentsInfo.ts 에서 studentsInfo2.ts로) 자동으로 실행되는 ngOnChange() 사용해보기.
studentsInfo2.ts 생성
app.component.html에 버튼 생성
(click)은 onClick과 같다. onChange()는 함수다. app.component.ts에 정의
onChange()를 누를때마다 students 값이 변화하게 함.
ngOnChanges를 사용하기 위한 새 컴포넌트 생성
ngOnChange.component.ts 에 ngOnChanges 사용
[student]를 받기 위해 @Input()을 사용
ngOnChanges(changeData: SimpleChanges)는 컴포넌트에 들어오는 값이 바뀌면 자동으로 실행
실시간으로 currentValue와 previousValue, firstChange 값을 보내준다. 그래서 실시간으로 변경되는 값을 알 수 있다.
출력
확인
from http://ljwoon94.tistory.com/44 by ccl(A) rewrite - 2021-05-22 17:00:56