Angular父组件触发子组件事件多次
创始人
2024-10-25 01:30:48
0

当父组件触发子组件事件多次时,可以采取以下解决方法:

  1. 确保子组件的事件监听器只被绑定一次。确保在父组件中,只将事件绑定到子组件的一个实例上。
// 父组件
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  triggerChildEvent() {
    // 确保只触发一次子组件事件
    this.childComponent.childEvent.emit();
  }
}


// 子组件
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent {
  @Output() childEvent: EventEmitter = new EventEmitter();

  handleChildEvent() {
    console.log('子组件事件触发');
  }
}
  1. 确保子组件的事件只被处理一次。在子组件中,可以使用一个标志位来确保事件只被处理一次。
// 子组件
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent {
  @Output() childEvent: EventEmitter = new EventEmitter();
  isEventHandled: boolean = false;

  handleChildEvent() {
    if (!this.isEventHandled) {
      console.log('子组件事件触发');
      this.isEventHandled = true;
    }
  }
}

这样,当父组件触发子组件事件多次时,子组件只会处理第一次触发的事件,后续的事件将被忽略。

相关内容

热门资讯

透视规律!wepoker辅助是... 透视规律!wepoker辅助是真的假的(透视)大唐麻将辅助软件(都是真的是有辅助下载)-哔哩哔哩1、...
透视数据!竞技联盟辅助(透视)... 透视数据!竞技联盟辅助(透视)杭麻圈辅助工具(果然是有辅助插件)-哔哩哔哩1)杭麻圈辅助工具辅助插件...
透视存在!wepoker黑侠辅... 透视存在!wepoker黑侠辅助器(透视)雀神广东麻将推倒胡辅助器下载(竟然有辅助app)-哔哩哔哩...
据目击者称!pokemmo手机... 据目击者称!pokemmo手机版透视脚本(透视)授权二厅辅助(果然真的是有辅助修改器)-哔哩哔哩1、...
透视总结!werplan免费挂... 透视总结!werplan免费挂下载(透视)新蛮王辅助(本来真的是有辅助辅助器)-哔哩哔哩新蛮王辅助是...
近日!aapoker脚本怎么用... 近日!aapoker脚本怎么用(透视)禅游指尖四川修改器(一贯有辅助工具)-哔哩哔哩所有人都在同一条...
此事迅速冲上热搜!aapoke... 此事迅速冲上热搜!aapoker免费透视脚本(透视)传送屋潮州激k辅助怎么打开(原来存在有辅助下载)...
近年来!wepoker永久免费... 近年来!wepoker永久免费脚本(透视)天天爱柳州有没有辅助器(真是真的有辅助安装)-哔哩哔哩1、...
昨日!wpk真吗(透视)万能游... 昨日!wpk真吗(透视)万能游戏辅助器脚本(真是是有辅助辅助器)-哔哩哔哩万能游戏辅助器脚本是不是有...
透视挂透视!德州之星扫描器(透... 透视挂透视!德州之星扫描器(透视)小程序微乐辅助器2.0(真是存在有辅助辅助器)-哔哩哔哩1、让任何...