【问题标题】:Trying to pass event from Parent to Child not working. Angular 8试图将事件从父级传递给子级不起作用。角 8
【发布时间】:2020-06-15 06:20:35
【问题描述】:

手风琴是父组件,子组件包含数据,因此我需要知道父组件何时更新扩展(单击),以便我可以调用 api。这是为了尽量减少 api 调用的次数。

我已经用 EventEmitters 尝试了很多东西,但它并没有按照我想要的方式工作。即使没有单击父级,该事件也会一直触发。 eventemitter 让我认为它应该只用于从子级触发父级中的事件。所以不要以为我用对了。

现在,我正在使用 @ViewChild 来实际访问 childs 方法来触发它。这工作正常,但我确实收到循环依赖警告,这也不好。

父级:=> PlannedMaintenanceComponent

@ViewChild(forwardRef(() => PlannedMaintenanceDetailComponent), { static: false })
private plannedMaintenanceDetailComponent: PlannedMaintenanceDetailComponent;

updateExpanded(id: string) {

    this.plannedMaintenanceDetailComponent.parentIsExpanded(this.isExpanded, id);
}

孩子:=> PlannedMaintenanceDetailComponent

 public parentIsExpanded(isExpanded: boolean, id: string) {
    this.plannedMaintenanceId = id;
    //call api
  }

当有人点击父组件时,如何在子组件中触发事件?

【问题讨论】:

    标签: angular typescript angular8


    【解决方案1】:

    我会使用 EventEmitter int PlannedMaintenanceDetailComponent,这样您就可以在该 EventEmitter 发出时在执行回调的父组件中订阅它。

    export class PlannedMaintenanceDetailComponent {
     isDropped: boolean;
     isDroppedEvent= new EventEmitter<boolean>()
     //..
    
     onClick() {
       this.isDropped = !isDropped() ;
       isDroppedEvent.emit(isDropped);
     }
    }
    

    然后在父类中

    private plannedMaintenanceDetailComponent: PlannedMaintenanceDetailComponent;
    ngOnInit() {
      plannedMaintenanceDetailComponent.isDroppedEvent.subscribe((isDropped) => {
       if (isDropped){
        call my api
       }
     })    
    }
    

    【讨论】:

    • 啊,我从来没有订阅过这个活动。谢谢你。我将在今天晚些时候试一试。
    • 我注意到我想扩展的一件事。父组件有手风琴。当它扩展时,它需要将事件发送给孩子。孩子需要调用 api 而不是父母。 (子项作为手风琴项生活,并在父项展开时显示数据)
    • 您也可以对这种行为进行建模:在父级上创建一个下拉事件dropDownEvent发射器,然后将其传递给子级,您可以在子级上使用@Input() dropEmitter: EventEmitter(boolean),在子级上使用&lt;app-child-componet [dropEmitter]=dropDownEvent&gt;&lt;/app-child-component&gt;父母。有了它,您可以订阅它并在孩子的回调函数上执行您的 api 调用
    • 太棒了。非常感谢。
    • 我实现了这个,奇怪的是事件触发了 4 次。 (我检查了一个简单的控制台日志)。我在孩子@Input() expandedEventEmitter = new EventEmitter&lt;boolean&gt;(); 中实现了这个,然后在 ngOnInit => this.expandedEventEmitter.subscribe(data =&gt; { if (data) { console.log(data); } })
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2021-02-09
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多