기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

SPA (Single-page Application)

SPA (Single-page Application) 데스크탑에 비해 성능이 낮은 모바일에 대한 니즈가 증가하면서 스마트폰을 통해 웹페이지를 출력하기 위해서는 기존 방식과는 다른 접근이 필요해졌다. 이를 위해 등장한 기법이 바로 SPA이다. Single-page application (SPA) 서버로부터 완전한 새로운 페이지를 불러오지 않고 현재의 페이지를 동적으로 다시 작성함으로써 사용자와 소통하는 웹 애플리케이션이나 웹사이트 SPA에서 HTML, JavaScript, CSS 등 필요한 모든 코드는 하나의 페이지로 불러오거나, 적절한 자원들을 동적으로 불러들여서 필요하면 문서에 추가하는데, 보통 사용자의 동작에 응답하게 되는 방식이다. SPA와의 소통은 웹 서버와의 동적인 통신을 수반하기도 한다. 이러한 접근은 연속되는 페이지들 간의 사용자 경험의 간섭을 막고, 애플리케이션이 더 데스크톱 애플리케이션처럼 동작하도록 만들어준다. 예를 들어 보통 웹 사이트처럼 여러 페이지가 있고 로그인, 회원가입, 글쓰기 등 복잡한 기능을 지원하지만, 이는 처음 호출된 HTML 상에서 필요한 데이터만 호출하여 화면을 새로 구성해 주는 것으로 실제로 페이지의 이동이 일어나지 않는다. 기존의 웹 사이트는 내용이 변하지 않아도 페이지를 이동할 때마다 서버에서 코드를 생성해 새로 읽고 클라이언트에서는 이 코드를 페이지에 렌더링하게 된다. SPA에서는 이러한 부분들이 처음 웹 사이트 접속 시 한 번만 요청되고 페이지를 이동할 때는 변경되는 view 부분만 데이터를 받아서 렌더링하기 때문에 속도가 빠르다. 불필요한 코드 요청이 줄어 처리량과 트래픽이 적어진다. 물론 SPA에도 단점은 있다. Google 같은 검색 엔진은 SPA를 색인화하는 데 어려움을 겪는다. 한 페이지 내에서 모든 동작을 진행하다 보니 URL이 변경되지 않아 검색의 색인이 어렵다. 대표적인 라이브러리 및 프레임워크로는 React, Angular, Vue가 있다. 장점 간편한 운영 배...

[Vue] Angular 2 대신에 Vue.js를 선택한 이유

[Vue] Angular 2 대신에 Vue.js를 선택한 이유 들어가며 이 글은 Medium 의 "Why we moved from Angular 2 to Vue.js(and why we didn't choose React)" 글을 번역한 글입니다. 항상 이상적일 수만은 없는 실제 프로젝트 여건에서 신중하게 프레임워크를 고민하고 선정해 나가는 과정을 상세하게 기술한 글입니다. Angular 2로 구축되어 있는 프로젝트를 업그레이드 & 마이그레이션 하는 과정에서 프로젝트의 현 상황과 여건을 반영한 프레임워크 선정 기준을 세우고, Vue.js 프레임워크를 적용해 나가는 개인 경험담이 담겨져 있습니다. 급격하게 요동치는 프론트엔드 프레임워크 시대에, 프론트엔드 개발자로서 항상 어떤 프레임워크를 선정해야 할지 고민하는 데 인사이트를 제공하는 글이 되길 바랍니다. 본문 우리는 최근에 Rever 라는 사이트에 Vue.js로 개발한 웹 페이지를 오픈했습니다. 16주 동안 641 개의 커밋이라는 강도 높은 개발 과정을 지나고 나니, Vue.js 도입하기를 잘했다는 생각이 듭니다. 8 달 전에 우리는 Angular 2를 쓰고 있었습니다. 정확하게 말하자면 Angular 2 베타 9 버전이었죠. 외주가 Angular 2로 제작해놓은 웹 사이트가 있었는데, UX/UI부터 설계까지 한 번도 만족한 적이 없었습니다. 심지어 어느 부분에 대해서는 Angular 2 자체가 맘에 들지 않았어요. 경험담을 더 얘기하기 전에, Angular 2 베타 9와 Angular 2.0는 완전히 다른 제품이라고 말하고 싶습니다. 그렇기 때문에 문제가 있었죠. Beta 9부터 2.0.0까지 8 개의 Beta 버전이 있었습니다. RC 8 개와 2.0.0 버전, 그리고 업그레이드까지 합치면 총 17 개의 버전이 있었죠. 우리는 Beta 9에서 2.0.0으로 업그레이드를 시도했지만, 상당히 많은 부분들이 호환되지 않아 업그레이드 작업이 버거워졌습니다. ...

(주)레터플라이 채용 정보: 프로그래밍을 생각하면 가슴이 뛰는 개발자...

(주)레터플라이 채용 정보: 프로그래밍을 생각하면 가슴이 뛰는 개발자... Angular.js, Python, MySQL 중 한 가지 언어에 뛰어나신 분도 좋고 개발 업무 전반적으로 센스가 있으신 분도 환영합니다. 맡은 업무를 성실하게 수행해 나갈 수 있는 책임감과 태도를 갖고계신 분, 그리고 항상 새로운 방법론에 도전하고 포기를 모르는 분일수록 저희와 더욱 잘 맞을 것 같습니다. Angular.js, Python, MySQL 중 한 가지 언어에 뛰어나신 분도 좋고 개발 업무 전반적으로 센스가 있으신 분도 환영합니다. 팀 내 뛰어난 풀스택 개발자분들이 Angular.js, Python, MySQL 모두 작업 가능하시니 오셔서 함께 배우며 즐겁게 작업하시면 됩니다. 맡은 업무를 성실하게 수행해 나갈 수 있는 책임감과 태도를 갖고계신 분, 그리고 항상 새로운 방법론에 도전하고 포기를 모르는 분일수록 저희와 더욱 잘 맞을 것 같습니다. 개발 업무: 레터플라이의 핵심 기능인 편지, 사진을 제작하는 레터에디터, 포토에디터 개발. 이 기능들은 "모바일 웹을 통한 출력제품 생산 자동화 기술"(특허 출원 준비중)로서 레터플라이에서 자체개발했습니다. 근무 지역: 광화문역 5번출구 바로 앞 근무 환경: 책임과 존중을 중요시하는 수평적인 분위기, 도전적이며 서로에게 배우는 문화 근무 시간: 10-19시, 출근시간 자유 지정. 급여: 연봉/스톡옵션 협의 지원 방법: 팀 지원하기 더 많은 내용은 더 많은 내용은 더팀스 에서 확인하세요! from http://theteams.tistory.com/721 by ccl(A) rewrite - 2020-03-20 09:20:18