Angular2 : 자식 구성 요소 액세스 부모 클래스 변수 / 함수
부모 구성 요소에 자식에 의해 변경 될 수있는 변수가 있습니다. 부모는 뷰에서이 변수를 사용하므로 변경 사항을 전파해야합니다.
import {Component, View} from 'angular2/core';
@Component({selector: 'parent'})
@View({
directives: [Child],
template: `<childcomp></childcomp>`
})
class Parent {
public sharedList = new Array();
constructor() {
}
}
@Component({selector: 'child'})
@View({template: `...`})
class Child {
constructor() {
//access 'sharedList' from parent and set values
sharedList.push("1");
sharedList.push("2");
sharedList.push("3");
sharedList.push("4");
}
}
JavaScript 참조 유형 (예 : Object, Array, Date 등)과 함께 입력 속성 데이터 바인딩을 사용하는 경우 부모와 자식 모두 동일한 / 하나의 개체에 대한 참조를 갖게됩니다. 공유 객체에 대한 모든 변경 사항은 부모와 자식 모두에게 표시됩니다.
부모의 템플릿에서 :
<child [aList]="sharedList"></child>
아이의 경우 :
@Input() aList;
...
updateList() {
this.aList.push('child');
}
자식 생성시 목록에 항목을 추가하려면 ngOnInit()후크를 사용합니다 (데이터 바인딩 된 속성이 해당 지점에서 초기화되지 않기 때문에 constructor () 아님).
ngOnInit() {
this.aList.push('child1')
}
이 Plunker는 공유 목록을 수정하는 부모 및 자식 구성 요소의 버튼 이 있는 작동 예제를 보여줍니다 .
자녀의 경우 참조를 다시 할당해서는 안됩니다. 예를 들어 자식에서이 작업을 수행하지 마십시오. this.aList = someNewArray;이렇게하면 부모 및 자식 구성 요소가 각각 두 개의 서로 다른 배열에 대한 참조를 갖게됩니다.
기본 유형 (예 : 문자열, 숫자, 부울)을 공유하려면이를 배열 또는 객체에 넣거나 (예 : 참조 유형에 넣음) 기본 유형이있을 emit()때마다 자식의 이벤트를 받을 수 있습니다 . 값 변경 (즉, 부모가 사용자 지정 이벤트를 수신하도록하고 자식은 EventEmitter출력 속성을 갖게 됩니다. 자세한 내용은 @kit의 답변을 참조하십시오.)
업데이트 2015/12/22 : Structural Directives 가이드 의 heavy-loader예 는 위에서 제시 한 기술을 사용합니다. 주 / 부모 구성 요소에는 자식 구성 요소에 바인딩 된 배열 속성이 있습니다. 하위 구성 요소 는 해당 배열에 있고 상위 구성 요소는 배열을 표시합니다.logspush()
NgModel과 NgForm과 같은 약간의 속임수는 어떻습니까? 부모를 공급자로 등록한 다음 부모를 자식 생성자에로드해야합니다.
이렇게 [sharedList]하면 모든 자녀 를 입을 필요가 없습니다 .
// Parent.ts
export var parentProvider = {
provide: Parent,
useExisting: forwardRef(function () { return Parent; })
};
@Component({
moduleId: module.id,
selector: 'parent',
template: '<div><ng-content></ng-content></div>',
providers: [parentProvider]
})
export class Parent {
@Input()
public sharedList = [];
}
// Child.ts
@Component({
moduleId: module.id,
selector: 'child',
template: '<div>child</div>'
})
export class Child {
constructor(private parent: Parent) {
parent.sharedList.push('Me.');
}
}
그런 다음 HTML
<parent [sharedList]="myArray">
<child></child>
<child></child>
</parent>
주제에 대한 자세한 정보는 Angular 문서 ( https://angular.io/guide/dependency-injection-in-action#find-a-parent-component-by-injection) 에서 찾을 수 있습니다.
부모 컴포넌트 선언에서 다음을 수행 할 수 있습니다.
get self(): ParenComponentClass {
return this;
}
In the child component,after include the import of ParenComponentClass, declare:
private _parent: ParenComponentClass ;
@Input() set parent(value: ParenComponentClass ) {
this._parent = value;
}
get parent(): ParenComponentClass {
return this._parent;
}
Then in the template of the parent you can do
<childselector [parent]="self"></childselector>
Now from the child you can access public properties and methods of parent using
this.parent
Basically you can't access variables from parent directly. You do this by events. Component's output property is responsible for this. I would suggest reading https://angular.io/docs/ts/latest/guide/template-syntax.html#input-and-output-properties
The main article in the Angular2 documentation on this subject is :
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child
It covers the following:
Pass data from parent to child with input binding
Intercept input property changes with a setter
Intercept input property changes with ngOnChanges
Parent listens for child event
Parent interacts with child via a local variable
Parent calls a ViewChild
Parent and children communicate via a service
'IT TIP' 카테고리의 다른 글
| 일부 호출이 작동하고 다른 호출이 실패하면 $ q.all ()은 어떻게됩니까? (0) | 2020.11.24 |
|---|---|
| Tomcat과 TomEE, TomEE 및 TomEE Plus의 차이점은 무엇입니까? (0) | 2020.11.24 |
| 사용자 인터페이스없이 Web API의 토큰 기반 인증 (0) | 2020.11.24 |
| Git : 이전 커밋에서 파일을 체크 아웃하고 HEAD로 수정 (0) | 2020.11.24 |
| 정적 const float가 허용되지 않는 이유는 무엇입니까? (0) | 2020.11.23 |