하위 구성 요소의 메서드 호출
다음과 같은 중첩 하위 구성 요소가 있습니다.
<app-main>
<child-component />
</app-main>
나의appMain
구성 요소가 하위 구성 요소에서 메서드를 호출해야 합니다.
하위 구성 요소에서 메서드를 호출하는 방법은 무엇입니까?
다음을 사용하여 요소에 대한 참조를 얻을 수 있습니다.
@ViewChild('childComponent') child;
어디에childComponent
템플릿 변수입니다.<some-elem #childComponent
>' 또는
@ViewChild(ComponentType) child;
어디에ComponentType
구성 요소 또는 지시의 유형이며, 다음은ngAfterViewInit
또는 이벤트 처리기 호출child.someFunc()
.
ngAfterViewInit() {
console.log(this.child);
}
부모와 자식은 데이터 바인딩을 통해 통신할 수 있습니다.
예:
@Component({
selector: 'child-component',
inputs: ['bar'],
template: `"{{ bar }}" in child, counter {{ n }}`
})
class ChildComponent{
constructor () {
this.n = 0;
}
inc () {
this.n++;
}
}
@Component({
selector: 'my-app',
template: `
<child-component #f [bar]="bar"></child-component><br>
<button (click)="f.inc()">call child func</button>
<button (click)="bar = 'different'">change parent var</button>
`,
directives: [ChildComponent]
})
class AppComponent {
constructor () {
this.bar = 'parent var';
}
}
bootstrap(AppComponent);
#f
하위 구성 요소에 대한 참조를 생성하고 템플릿에서 사용하거나 함수로 전달할 수 있습니다.상위 데이터는 다음을 통해 전달될 수 있습니다.[ ]
구속력이 있는
아들 구성 요소가 되는 것
@Component({
// configuration
template: `{{data}}`,
// more configuration
})
export class Son {
data: number = 3;
constructor() { }
updateData(data:number) {
this.data = data;
}
}
아버지 구성 요소를 갖는 것
@Component({
// configuration
})
export class Parent {
@ViewChild(Son) mySon: Son;
incrementSonBy5() {
this.mySon.updateData(this.mySon.data + 5);
}
}
아버지의 템플릿에서
<son></son>
<button (click)="incrementSonBy5()">Increment son by 5</button>
이 솔루션은 하나에 대해서만 작동합니다.<son></son>
인스턴스가 상위 템플릿에 있습니다.둘 이상의 인스턴스가 있는 경우 템플릿의 첫 번째 인스턴스에서만 작동합니다.
하위 구성 요소에 액세스하는 가장 좋은 방법은 @ViewChild입니다.
예를 들어 AppMainComponent에 중첩된 ChildComponent가 있다고 가정해 보겠습니다.
// app-main.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-main',
template: `
<child-component />
`
})
export class AppMainComponent {}
하위 구성 요소에서 일반 메서드를 호출하려고 합니다.
// child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'child-component',
template: '{{ greeting }}'
})
class ChildComponent {
greeting: String = 'Hello World!';
clear() {
this.greeting = null;
}
}
ChildComponent 클래스, ViewChilddecorator를 가져오고 구성 요소의 클래스를 쿼리로 전달하여 이 작업을 수 있습니다.이렇게 하면 사용자 지정 변수에 저장된 하위 구성 요소의 인터페이스에 액세스할 수 있습니다.다음은 예입니다.
// app-main.component.ts
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './components/child/child.component';
@Component({
selector: 'app-main',
template: `
<child-component />
`
})
class ChildComponent {
@ViewChild(ChildComponent)
child: ChildComponent;
clearChild() {
this.child.clear();
}
}
주의! 하위 보기는 ngAfterViewInit 이후에만 사용할 수 있습니다.
Angular는 구성 요소의 뷰와 하위 뷰를 초기화한 후에 응답합니다.첫 번째 ngAfterContentChecked() 후에 한 번 호출됩니다.구성 요소 전용 후크입니다.
메소드를 자동으로 실행하려면 이 라이프사이클 후크 내에서 메소드를 실행해야 합니다.
ViewChildren 장식기를 통해 하위 구성요소의 QueryList를 가져올 수도 있습니다.
import { Component, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from './components/child/child.component';
...
@ViewChildren(ChildComponent)
children: QueryList<ChildComponent>;
QueryList는 자식 변경사항을 구독할 수 있는 등 매우 유용할 수 있습니다.
템플릿 참조 변수를 만들고 ViewChild 장식기를 통해 액세스할 수도 있습니다.
언급URL : https://stackoverflow.com/questions/31013461/call-a-method-of-the-child-component
'programing' 카테고리의 다른 글
Angular 4 오류: HttpClient에 대한 공급자 없음 (0) | 2023.07.29 |
---|---|
반응형 레이아웃에 요소를 숨깁니까? (0) | 2023.07.29 |
Spring과 Spring MVC 프레임워크의 차이점은 무엇입니까? (0) | 2023.07.29 |
루트 장치에서 실행 중인지 확인 (0) | 2023.07.29 |
로드 밸런서에 클라이언트: 회의에 사용할 수 있는 서버가 없습니다. (0) | 2023.07.24 |