code

하위 구성 요소의 메서드 호출

codestyles 2020. 10. 26. 08:00
반응형

하위 구성 요소의 메서드 호출


다음과 같은 중첩 된 자식 구성 요소가 있습니다.

<app-main>
    <child-component />
</app-main>

appMain구성 요소는 자식 구성 요소에서 메서드를 호출해야합니다.

하위 구성 요소에서 메서드를 호출하는 방법은 무엇입니까?


다음을 사용하여 요소에 대한 참조를 얻을 수 있습니다.

@ViewChild('childComponent') child;

여기서 childComponent인 템플릿 변수 <some-elem #childComponent> '또는

@ViewChild(ComponentType) child;

여기서는 ComponentType구성 요소 또는 지시문의 유형이고 in 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>

This solution only works for one <son></son>instance in the parent template. If you have more than one instance only will work in the first one of the template.


The best way to access a child component is @ViewChild.

Let's say you have AppMainComponent with a nested ChildComponent from your example.

// app-main.component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'app-main',
    template: `
        <child-component />
    `
})

export class AppMainComponent {}

You want to invoke a clear method from your ChildComponent.

// child.component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'child-component',
    template: '{{ greeting }}'
})

class ChildComponent {
    greeting: String = 'Hello World!';

    clear() {
        this.greeting = null;
    }
}

You can accomplish it by importing the ChildComponent class, ViewChild decorator and pass component's class in it as a query. This way, you would have access to the ChildComponent's interface stored in the custom variable. Here is an example:

// 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();
    }
}

Notice! Child view becomes available only after ngAfterViewInit.

Respond after Angular initializes the component's views and child views. Called once after the first ngAfterContentChecked(). A component-only hook.

If you want to execute method automatically, you need to do it inside this lifecycle hook.

You can also get a QueryList of child components via ViewChildren decorator.

import { Component, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from './components/child/child.component';

...

@ViewChildren(ChildComponent)
children: QueryList<ChildComponent>;

QueryList might be very useful, e.g. you can subscribe for children changes.

It's also possible to create template reference variables and get access to them via the ViewChild decorator.

참고URL : https://stackoverflow.com/questions/31013461/call-a-method-of-the-child-component

반응형