【问题标题】:How to call a method in a child component from a parent component?如何从父组件调用子组件中的方法?
【发布时间】:2020-06-15 03:00:25
【问题描述】:

好的,标题可能有点混乱。我的子组件在它自己的模块中,并且正在使用父组件不可用的服务。

我想在单击按钮时更改子组件中的一些值,并且正在搞乱并设置这样的东西。

@Component({
 selector: 'app-parent-component'
 template: `
 <button (click)="refreshData()" />
 <app-child-component> </app-child-component>
`
})
export class ParentComponent{
 refreshData() {
   ChildComponent.runRefresh()
 }
}

@Component({
 selector: 'app-child-component'
 template: ``
})
export class ChildComponent{
 static runRefresh() {
   console.log('refreshing')
   // Do things involving data on a service scoped to this component/module
 }
}

我很好奇这种方法是否存在固有的问题?有没有更好的方法来解决这个问题。我熟悉检查 NgOnChanges 事件的变化。

我想我想要做的是在子组件内部调用一个方法,该方法使用来自父组件的作用域服务上的子组件资源。

编辑:也知道使用@ViewChild 并且不使子组件方法静态。也许这是唯一“正确”的方式?

【问题讨论】:

  • 我能想到的只有一个,如果你有多个组件实例,你要刷新哪个组件?我想我宁愿选择有自己的方式通过@Input setter 或其他方式触发刷新的组件。
  • @IngeOlaisen 刷新更多的是刷新数据并调用api。实际上并没有刷新浏览器中的任何内容。我知道我可以使用 ViewChild 并在 上添加参考。只是在寻找新的方法
  • 为什么runRefresh 是静态的?
  • @ConnorsFan 这只是静态的,因为我正在试验。我喜欢你的解决方案。谢谢!

标签: angular


【解决方案1】:

如果runRefresh是子组件的公共方法:

export class ChildComponent{
  public runRefresh() {
    ...
  }
}

你可以在父模板中直接调用它,在template reference variable的帮助下引用子组件:

<button (click)="child.runRefresh()" />
<app-child-component #child></app-child-component>

请参阅this stackblitz 以获取演示。

【讨论】:

    【解决方案2】:

    最简单的方法是编写一个提供事件的服务,在父级中发出,在子级中订阅。

    另一种方式:

    您可以编写一个提供组件引用的指令:

    import { Directive, TemplateRef } from '@angular/core';
    
    @Directive({
      selector: '[selectordirective]',
    })
    export class SelectorDirective  {
      constructor(public cmpRef: ChildComponent) { }
    }
    

    把它贴在你的孩子身上:

    <app-child-component selectordirective> </app-child-component>
    

    使用 ViewChild 读取ParentComponent中的引用:

    @ViewChild(SelectorDirective) child !: SelectorDirective;
    
      ngAfterViewInit() {
        child.cmpRef.runRefresh()
      }
    

    【讨论】:

    • 为什么不只是 ChildComponent 的 ViewChild?
    猜你喜欢
    • 2021-05-02
    • 2016-12-08
    • 2018-06-08
    • 2020-05-19
    • 2020-06-27
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多