부모 구성 요소의 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) {
}
}
또 다른 방법은 자식에게 부모 성분을 주입하는 것이겠지만, 그 성분들은 서로 강하게 연결되어 있을 겁니다...
아래는 최근에 나에게 효과가 있었던 코드입니다.
각5+
class ChildComponent {
@Output() myEvent = new EventEmitter<string>();
callParent() {
this.myEvent.emit('eventDesc');
}
}
인ParentTemplate의 견본
<child-component (myEvent)="anyParentMethod($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()
}
상위 구성 요소를 하위 구성 요소에 주입할 수 있습니다.
자세한 내용은 을 참조하십시오.
- 자식 구성 요소에 부모 구성 요소를 주입하려면 어떻게 해야 합니까?
- Angular 2 자식 구성 요소는 부모 구성 요소를 나타냅니다. 이렇게 하면 다음을 확인할 수 있습니다.thefunction()부모가 A일 때만 호출됩니다.body.component.
constructor(@Host() bodyComp: BodyComponent) {
그렇지 않은 경우 사용@Output()자식에서 부모로 통신하는 것이 선호됩니다.
상위 html:
<child [parent]="this"></child>
하위 구성 요소에서:
@Input() parent: ParentComponent;
// then do whatever with `this.parent`
행사는 각자의 자리가 있지만, 이보다 더 간단한 것은 없습니다.
언급URL : https://stackoverflow.com/questions/35940984/angular2-call-function-of-parent-component
'programing' 카테고리의 다른 글
| IE 문자열에 숫자를 지정할 수 있습니다. (0) | 2023.09.11 |
|---|---|
| C에서 "==" 연산자의 반환 값 (0) | 2023.09.11 |
| Postgre와 동등한 MySQL은 무엇입니까?SQL의 설명 분석 (0) | 2023.09.11 |
| php 5.6에서 mariadb 10.1에 삽입 일부 행을 삽입하지 않음 (0) | 2023.09.11 |
| CSS 호버 이벤트에서 다른 디브의 스타일링을 변경할 수 있습니까? (0) | 2023.09.06 |