부모 구성 요소의 angular2 호출 함수
파일을 업로드 할 수있는 업로드 구성 요소가있는 앱이 있습니다. 그것은에 포함됩니다 body.component
.
업로드 할 BodyComponent.thefunction()
때 부모 구성 요소의 함수 (예 :)를 사용해야합니다 ( 데이터 업데이트를위한 호출 수행). 그러나 부모가 구체적으로 body.component
. 업로드는 다른 동작으로 다른 곳에서도 사용될 수 있습니다.
같은 뭔가 parent(this).thefunction()
, 어떻게 할까?
하위 구성 요소에 사용자 지정 이벤트를 만듭니다. 그런 것 :
@Component({
selector: 'child-comp',
(...)
})
export class ChildComponent {
@Output()
uploaded = new EventEmitter<string>();
uploadComplete() {
this.uploaded.emit('complete');
}
상위 구성 요소가이 이벤트에 등록 할 수 있습니다.
@Component({
template `
<child-comp (uploaded)="someMethod($event)"></child-comp>
`,
directives: [ ChildComponent ]
})
export class ParentComponent {
(...)
someMethod(event) {
}
}
또 다른 방법은 부모 구성 요소를 자식 구성 요소에 삽입하는 것이지만 서로 강력하게 연결됩니다.
아래는 최근에 나를 위해 일했습니다.
Angular5
class ChildComponent {
@Output() myEvent = new EventEmitter<string>();
callParent() {
this.myEvent.emit('eventDesc');
}
}
에서 ParentTemplate
의 템플릿
<child-component (myEvent)="anyParentMehtod($event)"
관련 이벤트가없는 솔루션.
(원래 부모의 컨텍스트 유지)에 속하는 ChildComponent
메서드를 호출하고 싶다고 가정합니다 .myMethod()
ParentComponent
상위 구성 요소 클래스 :
@Component({ ... })
export class ParentComponent {
get myMethodFunc() {
return this.myMethod.bind(this);
}
myMethod() {
...
}
}
상위 템플릿 :
<app-child [myMethod]="myMethodFunc"></app-child>
하위 템플릿
@Component({ ... })
export class ChildComponent {
@Input() myMethod: Function;
// here I can use this.myMethod() and it will call ParentComponent's myMethod()
}
부모 구성 요소를 자식 구성 요소에 삽입 할 수 있습니다.
자세한 내용은
- 부모 구성 요소를 자식 구성 요소에 어떻게 주입합니까?를 참조하십시오 .
- 각도이 하위 구성 요소는 상위 구성 요소를 말한다 당신이 보장 할 수 있습니다이 방법은 thefunction()
부모가있는 경우에만 호출됩니다 body.component
.
constructor(@Host() bodyComp: BodyComponent) {
그렇지 않으면 사용하여 @Output()
자식에서 부모로 의사 소통 하는 것이 좋습니다.
참고 URL : https://stackoverflow.com/questions/35940984/angular2-call-function-of-parent-component
'Program Tip' 카테고리의 다른 글
SQL Server에서 VARCHAR 열의 최대 길이 검색 (0) | 2020.10.25 |
---|---|
'ProviderPackage'패키지가 올바르게로드되지 않았습니다. (0) | 2020.10.25 |
iOS에서 수정 된 백그라운드 첨부 파일을 복제하는 방법 (0) | 2020.10.24 |
INSERT INTO를 사용하여 여러 값 삽입 (SQL Server 2005) (0) | 2020.10.24 |
C ++ 멤버 함수에서 "if (! this)"는 얼마나 나쁩니 까? (0) | 2020.10.24 |