programing

Angular 2 - 상위 항목에서 하위 항목에 대해 메서드를 트리거하는 방법

css3 2023. 8. 8. 21:46

Angular 2 - 상위 항목에서 하위 항목에 대해 메서드를 트리거하는 방법

@Input을 통해 부모로부터 자녀에게 데이터를 보낼 수도 있고, @Output을 사용하여 자녀에게서 부모에 대한 메서드를 호출할 수도 있습니다. 하지만 저는 그 반대의 방법, 즉 부모로부터 자녀에 대한 메서드를 호출하고 싶습니다.기본적으로 다음과 같은 것입니다.

@Component({
  selector: 'parent',
  directives: [Child],
  template: `
<child
  [fn]="parentFn"
></child>
`
})
class Parent {
  constructor() {
    this.parentFn()
  }
  parentFn() {
    console.log('Parent triggering')
  }
}

그리고 아이:

@Component({
  selector: 'child',
  template: `...`
})
class Child {
  @Input()
  fn() {
    console.log('triggered from the parent')
  }

  constructor() {}
}

배경은 일종의 "취득" 요청입니다. 즉, 아이로부터 최신 상태를 얻기 위한 것입니다.

이제 서비스와 주제/관찰을 통해 이를 달성할 수 있다는 것을 알고 있습니다. 하지만 이보다 더 간단한 것은 없을까요?

제 생각에 당신이 찾고 있는 것은 다음과 같습니다.

https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable

https://angular.io/guide/component-interaction#parent-calls-an-viewchild

템플릿 내의 로컬 변수 또는 를 사용하여 하위 속성 및 메서드에 액세스할 수 있습니다.@ViewChild부모 구성요소 클래스의 장식자입니다.

@ViewChild맞는 해결책이지만, 위에 링크된 문서가 저에게는 다소 불분명했기 때문에 이해하는 데 도움이 되는 좀 더 친절한 설명을 전달합니다.

한 잔 하자꾸나ChildComponent메소드 포함:

whoAmI() {
  return 'I am a child!!';
}

그리고 '@ViewChild' 기법을 사용하여 위의 메서드를 호출할 수 있는 상위 구성 요소:

import { Component, ViewChild, OnInit } from '@angular/core';

import { ChildComponent } from './child.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  @ViewChild(ChildComponent) child: ChildComponent;

  ngOnInit() {
    console.log(this.child.whoAmI()); // I am a child!
  }
}

언급URL : https://stackoverflow.com/questions/37635404/angular-2-how-to-trigger-a-method-on-a-child-from-the-parent