기본 콘텐츠로 건너뛰기

Angular2 | Component Interaction

Angular2 | Component Interaction

How do components communicate with each other?

The most confusing part with angular was interaction among components. This is because I didn't spend the time to study fundamentals, sending data back and forth was just too confusing. In the official Angular document, component interaction is explained in 5 ways. First 4 are straightforward but the last one about the service is challenging. I'll get back to that after studying the service first.

Angular를 처음 사용했을 때 가장 어려웠던 것은 기초를 공부할 시간이 없이 바로 실무로 투입이 되다 보니..

간단한 컴포넌트를 만들어서 사용하는 것이 너무 어렵고 시간도 오래 걸렸다.

처음에는 컴포넌트를 왜 만드는지.. 조차 모르고 그냥 막 다 copy and paste 하느라 아주 힘들었던 기억이 난다.

그래서 지금이라도 기초를 다시 잡으려고 한다. 시간을 내서 doc을 읽어보니 왜 이해가 되는 거같지?

도큐먼트에서는 component interaction을 할 수 있는 방법을 5가지를 설명한다.

여기서 첫 번째 4개는 금방 이해할 수 있었다. 하지만 5번째는 아직 100% 이해하지 못해서 서비스 쪽 개념을 다시 공부하고 마지막 것을 정리해야겠다.

1. Pass data from parent to child with input binding .

부모 컴포넌트에서 자식 컴토넌트로 데이터를 보낼때는 input binding을 사용한다.

Parent Component

@Component({ selector : 'app-parent', template : ` . ` }) export class ParentComponent{ public hero: string = Superman; // A variable called hero which has a value of Superman public master: string = 'Batman'; // Master라는 변수를 선언하고 Batman 값을 변수에 넣는다.

}

Child Component

@Component({ selector : 'app-child', template : `My name is {{hero}}, my best friend is {{master}} `, // My name is Superman, my best friend is Batman. // 부모 클라스에서 input binding으로 hero, master값을 받아 오기 때문에 위에처럼 찍히는 것이다. }) export class Child Component{ @Input() // with this input annotation you are telling angular that you are getting this value from your parent component. public hero: string;

@Input('master') // @input을 선언하면 부모클라스에서 값을 받아온다는 뜻이다. public masterName : string;

public _name: string ;

// input 으로 받아온 값을 가로채서 새로운 값을 주거나 trim 같은 메소드를 사용해서값을 변경할수 있다. // Intercept input property changes with a setter @Input() —> if some setting is needed for an input set name(name: string) { this._name = (name && name.trim()) || ''; }

}

2. Parent listens to child event

부모가 자식한테서 값을 받아올때는 자식에서 뱉는(?) 이벤트를 기다린다

Parent Component

@Component({ selector : 'app-parent', template : ` // Here heroChangeEvent in () is the variable in parent component with @output(). And the changeHeroName() is a method that is called when heroCHangeEvent is emitted. Here $event parameter is used to transfer data. // heroChangeEvents는 부모 컴포넌트에서 만든 변수이다. heroChangeEvent.emit()을 하면 여기로 온뒤에 changeHeroName()을 콜하는 것이다. // 여기서 파라미터로는 $event를 이용해서 데이터를 넘긴다. The hero has changed to {{ heroName }} ` // The hero has changed to WonderWoman }) export class ParentComponent{

public heroName: string;

// Child component 에서 emit 을 하면 여기로 연결해놨으니깐 거기서 보낸 name을 받아서 로컬 변수에 넣어서 화면에 보여지는 것이다 public changeHeroName(name) {

this.heroName = name;

}

}

Child Component

@Component({ selector: 'app-child', // When div is clicked change method is called. Div를 클릭하면 change()메소드를 탄다 template : `Click to change hero `, }) export class Child Component{ @Output() // with output annotation you are making custom event. public heroChangeEvent : new EventEmitter(); // output annotation 으로 선언한 heroChangeEvent를 이용해서 부모 컴포넌트로 이벤트 전파

public change() { // heroChangeEvent.emit() 은 Parent Component 에 선언되어있는 (heroChangeEvent)="changeHeroName()" 으로 가서 changeHeroName()를 부르게 되는 것이다 // heroChangeEvent.emit(and what you want to send to the parent component) calls (heroChangeEvent)="changeHeroName()" this statement in parent component. So when you emit changeHeroName method is called. this.heroChangeEvent.emit('Wonderwoman'); }

}

3. Parent interacts with child with local variable

변수를 선언해서 부모클라스에서 자식 클라스와 interact 한다.

By creating a template reference variable for the child element and then reference that variable within the parent template.

Parent Component

@Component({ selector : 'app-parent', template : ` // #childComponent is naming a local variable to the child Component. Now with childComponent variable, parent component can get access to child components variables and methods. // # 뒤에 오는 단어는 childComponent를 새로운 변수에 담는 것이다. 그래서 #childComponent라고 지었으면 childComponent.minute로 . 을 이용해서 자식 컴포넌트에 접근할 수 있다 {{childComponent.getCurrentDay}} {{childComponent.hour}} ` // Wednesday 50 }) export class ParentComponent{

}

Child Component

@Component({ selector: 'app-child', template : ` `, }) export class Child Component{ public minute : number = 3; public second : number = 60; public hour : number = 50;

public getCurrentDay() {

return 'Wednesday'; } }

4. Parent calls a viewChild()

ViewChild()를 이용해서 자식 컴포넌트에 접근한다.

The local variable approach is easy but it is only limited to the parent template. The parent component itself has no access to the child.

Inject the child component into the parent as a ViewChild when you need to read and write child component values or must call child component methods.

3번 같은 경우에 컴포넌트를 변수에 담아서 사용하면 쉽고 간단하지만 template안에서만 가능하기 때문에 사용성에 한계가 있다.

Component에 자식 컴포넌트를 주입해서 사용하는 방법이 viewChild()방법이다

@ViewChild(ChildComponent) private childComponent : ChildComponent;

public numberOfSeconds: number;

ngAfterViewInit() { // 3번이랑 비슷하게 위에 this.childComponent 를 이용해서 . 을 통해 child component에 접근할수 있다. this.numberOfSeconds = childComponent.seconds;

}

5. Parent and children communicate via service

부모, 자식 컴포넌트는 서비스를 이용해서 서로에서접근한다.

Parent and children share a service whose interface enables bi-directional communication within the family.

The scope of the service instance is the parent component and its children. Components outside this component subtree have no access to the service or their communications.

--> 여기는 조금 후에 정리 예정

from http://vitabrevis2.tistory.com/22 by ccl(A) rewrite - 2020-03-07 11:55:31

댓글

이 블로그의 인기 게시물

[aws] deploy Angular app with s3 | AWS S3로 angular 앱 배포하기

[aws] deploy Angular app with s3 | AWS S3로 angular 앱 배포하기 angular project를 빌드한다 ng build --prod 그러면 dist 폴더가 생긴다. dist 폴더 안에 있는 아이들을 사용한다. 아마존 s3 콘솔로 이동 https://s3.console.aws.amazon.com/s3/home?region=ap-northeast-2 새로운 Bucket 을 생성한다(Create bucket). 버킷 이름은 고유하게 짓는다. 버킷 생성후 properties tab > static website hosting을 클릭한다. index document는 index.html은 쓴다. properties > static website hosting Permission tab 에서 권한을 수정한다. overview tab 에서 필요한 파일 업로드 dist 폴더 안에 있는 파일들을 업로드 한다. bucket policy 설정 properties > static website hosting > endpoint 클릭하면 서버에 올라간 앱을 확인 할 수 있다 일단 angular 앱을 올리긴 했는데.. 이걸로는 아무것도 할 수 었다. django로 만든 서버를 올리고 database를 연결하고 그것을 지금 이 angular 앱과 연결해야한다. 아직 어떻게 해야 할지는 모르겠음 계속 삽질 중. 그래도 angular app 하나 올라갔는데 재밌네 from http://paigeblog.tistory.com/18 by ccl(A) rewrite - 2020-03-25 16:20:22

Angular Lazy-loading-ngmodules 사용해보기

Angular Lazy-loading-ngmodules 사용해보기 재미있는 프레임워크공부/Angular 2+ Lazy-loading-ngmodules를 사용하는 이유 SPA(Single Page Application)의 단점인 초기 구동 속도를 Angular로 피해갈 수는 없다. 프로젝트가 커지면 커질 수록 더 초기 구동 속도가 느려질 것이다. 그래서 이번 시간에는 초기 구동 시 전체 모듈을 불러오지 않고 관련한 모듈 페이지 로딩 시 불러올 수 있게 구글에서 만들어 놓은 Lazy-loading-ngmodules에 대해 알아보자. Lazy-loading-ngmodules를 먼저 알기 전 Angular route 기능에 대해 이해하고 들어갔으면 좋겠다. 자 그럼 이제 시작해보자. 1. app-routing (root)를 위한 app-routing.module.ts 를 만들어 보자 만약 새로운 프로젝트를 시작한다면 아래의 명령어를 치면 module을 자동적으로 생성해준다. ng new (프로젝트 이름) --routing 기존에 프로젝트에 적용하려고 한다면 app-routing.module.ts를 만들고 그 안에 아래의 내용들을 집어 넣는다. import { NgModule } from '@angular/core' ; import { Routes, RouterModule } from '@angular/router' ; const routes : Routes = []; @ NgModule ({ imports: [RouterModule. forRoot (routes)], exports: [RouterModule] }) export class AppRoutingModule { } CLI을 이용하면 자동적으로 AppModule에 import 되지만 직접 생성하였기 때문에 AppRountingModule을 app.module.ts에 import 해준다. 2. 이제 서브 라우팅을 생성하기 위해 새로운 ...