簡體   English   中英

Angular 2 - 如何從父級觸發子對象的方法

[英]Angular 2 - How to trigger a method on a child from the parent

可以通過@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() {}
}

背景是一種“獲取”請求,即從孩子獲得最新狀態。

現在我知道我可以通過服務和Subject / Observable實現這一點,但我想知道是否有更直接的東西?

我想這些可能就是你要找的東西:

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!
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM