기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

1. Welcome to React!

1. Welcome to React! 본 포스팅은 리액트를 처음으로 공부하기 시작하는 사람들을 위해 제작되었다. 구글에 영어로 react라고만 쳐봐도 기본적인 개념을 배울만한 블로그는 아주 많지만 막상 처음부터 하나하나 따라할 수 있는 튜토리얼과 같은 게시글이 없는 것 같아 이 부분에 초점을 맞춰 포스팅을 써보려 한다. 자바스크립트의 라이브러리 우선 리액트는 페이스북이 직접 개발한 자바스크립트의 라이브러리이다. 즉, 문법과 기능에 확장이나 변화가 있을 수는 있지만 그 뼈대는 자바스크립트에 있다는 것이다. 따라서 리액트를 공부하기 전에 자바스크립트의 기본적인 변수선언(const, let, var 등) 같은 문법을 알아둔 후 공부하는 것이 좋다. 참고하면 좋을만한 사이트 : https://opentutorials.org/course/743 Virtual Dom 필자가 리액트를 공부하며 처음으로 느낀 장벽은 바로 virtual DOM이라는 개념이다. 이 개념에 대해 구글에 검색해본 결과 다음과 같이 요약할 수 있다. 변한 부분만 다시 그린다. 이는 다시 말하면 리액트가 출시되기 전까지 모든 프레임워크는 변하지 않은 부분도 불필요하게 다시 그리고 렌더링 했다는 것이다. 아래에서 Angular라는 구글의 웹 개발 프레임워크와 React의 차이를 예시를 들어 비교해보자. 출처 - 블로그 : http://blog.naver.com/PostList.nhn?blogId=songc7 위의 두 그림을 차례로 그린다고 가정하자. 우선 누가 어떤 방법으로 그리던 모두 처음 그림은 캔버스에 백지상태부터 그려야 한다. 하지만 두번째 그림을 이어서 그려야 할때 Angular는 새로운 캔버스에 전체 그림을 다시 그려서 우리에게 보여주는 반면 리액트는 처음과 두번째 그림을 비교해서 달라진 부분만 찾아서 그린 후 원래 그림에 덮어서 보여준다. 여기서 "속도"의 차이가 명확하게 발생한다. Angular을 포함한 기존의 프레임워크들은 전체 그림(

[django] django rest framework 로그인 과정 | 장고 로그인 | 인증...

[django] django rest framework 로그인 과정 | 장고 로그인 | 인증... django 는 기능이 참 너무 많다 ^^; 지금은 서버는 django로, 프론트는 angular를 붙여서 간단한 웹을 만들어 보려고 한다. 웹 만들때 항상 회원가입/로그인 기능은 맨 앞에 구현한다. 어떻게 구현하면 좋을까... 찾아보다가 이 기능을 구현할 수 있는 방법이 너무 많아서 정보를 찾기 더 어려웠다. 일단 나는 django에서 django rest framework라는 것을 사용해서 API를 만드려고 한다. 순수 django 튜토리얼에는 바로 template 랑 연결해서 설명하는 부분이 많았다. 나는 그냥 API 만 만들고 싶다고!! 그래서 찾은 것이 django REST framework. https://www.django-rest-framework.org/api-guide/authentication django REST framework 설치 using pip pip install djangorestframework settings.py INSTALLED APPS 에 추가해야함 INSTALLED_APPS = [ ... 'rest_framework', ] django REST framework 에서도 인증 관련해서 제공하는 것이 1개가 아닌 여러 개다. 나는 그중에 TokenAuthentication을 이용해서 로그인을 구현해 보려고 한다. TokenAuthentication Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. 이렇게 나와있어서 내가 하려는 것과 일치해서 이걸로 결정 ~ 솔직히 처음 로그인을 구현하려고 하면 도대체 그 과정이 어떻게 되는지 모를 수 도 있다. 나는 쉽게 정리하면 아래와 같은 과정이라고 생각한다. 로그인 로그아웃

개발자를 위한 React.js 툴 및 리소스

개발자를 위한 React.js 툴 및 리소스 개발자를 위한 React.js 툴 및 리소스 페이스 북이 2013 년에 라이브러리를 처음 공개 한 이후 React.js의 인기는 빠르게 증가하고 있습니다.이 프로젝트는 Github에서 다섯 번째로 가장 많이 출연 한 오픈 소스 프로젝트이며 React 개발자를위한 구인 광고도 크게 증가하고 있습니다. React는 사용자 인터페이스를 구축하기위한 간단한 JavaScript 프레임 워크입니다. 가장 두드러진 예로는 Facebook 및 Instagram이 있습니다. React는보다 간단한 구조와 성능 최적화에 중점을 둔 Angular 또는 Backbone과 같은 MVC 프레임 워크에 대한 대안을 제공합니다. React가 앞으로 몇 년 동안 웹 개발 환경을 확실히 정의 할 것이기 때문에이 기사에서는 React 개발 영역에 발을 딛는 데 도움이되는 개발자 툴킷을 제공하고자합니다. 공식 React.js 문서 Facebook은 개발자에게 React의 주요 개념에 대한 자세한 문서를 제공합니다. 문서 외에도 React를 사용하여 대화 형 틱택 토 게임을 구축하는 방법에 대한 훌륭한 자습서와 React 개발자를위한 토론 포럼을 찾을 수 있습니다. 문서는 오픈 소스이므로 원하는 경우 편집 할 수도 있습니다. 공식 페이스 북 문서 React.js Github Repo React Github Repo에서 필요할 때마다 React의 소스 코드를 확인할 수 있습니다. 현재 개발 상태에 대한 정보를 유지하려면 문제, 중요 시점 및 최신 풀 요청을 살펴볼 수도 있습니다. 문제가 발생하면 문제 해결 가이드를 약간 연구하는 것이 좋습니다. React.js Github Repo 안녕하세요 월드 스타터 코드 빠른 반응을 원한다면 Codepen에서이 "Hello World"대화식 데모로 시작할 수 있습니다. 필요한 모든 자산과 시작 코드도 포함되어 있습니다. Babel도 켜져 있으므로 ECMAScri