【问题标题】:angular 2 generic click event in child component子组件中的 Angular 2 通用单击事件
【发布时间】:2019-06-07 21:16:59
【问题描述】:

有一个子组件用于 Angular Web 应用程序的许多页面。子组件有一个调用函数的(click) 事件。包含此子组件的每个页面都在点击事件时调用具有不同参数的不同函数。

如果父级不同,我怎样才能使这个(click) 事件通用或动态调用不同的函数?

// In one component    
(click)="saveData(types, functions)"

// On another component
(click)="showFunctions(index, areas, types)"

在具有不同点击事件的多个页面中使用单个子组件,我们如何做到这一点?

提前谢谢你。

【问题讨论】:

  • 不,因为我通过子组件的参数传递了一些数据。所以为了将它传递给更高的组件,我正在使用 eventEmmiter.
  • 输出和输入将能够帮助您实现这一目标。或者 EventEmitter 像下面的答案

标签: angular


【解决方案1】:

孩子:

<button type="button" (click)="onMyClick()">Click<button>

@Output() myClick = new EventEmitter();

onMyClick() {
    this.myClick.emit();
}

家长:

<my-child-cmp (myClick)="firstFunction()"></my-child-cmp>

firstFunction() {
   // whatever
}

父母2:

<my-child-cmp (myClick)="secondFunction()"></my-child-cmp>

secondFunction() {
   // whatever
}

希望对您有所帮助。如果您需要更多详细信息,请告诉我。

顺便说一句,如果您需要将一些数据从孩子发送给您的父母,您可以这样做:

孩子:

<button type="button" (click)="onMyClick()">Click<button>

@Output() myClick = new EventEmitter();

onMyClick() {
    this.myClick.emit(something);
}

家长:

<my-child-cmp (myClick)="firstFunction($event)"></my-child-cmp>

firstFunction(event: Event) {
   console.log(event); // You will see something here))

}

更新:

如果我们需要从父母向孩子发送数据

父母

data: any;

ngOnInit() {
  this.data = 'hello world';
}

<app-child [settings]="data"></app-child>

孩子:

@Input() settings: any;

ngOnInit() {
  console.log(this.settings);
}

【讨论】:

  • 这回答了我的问题。谢谢
  • 感谢您的回答。如果我们需要从父母向孩子发送类似的事件怎么办??
猜你喜欢
  • 2018-07-13
  • 2017-11-01
  • 1970-01-01
  • 2017-05-25
  • 2017-05-30
  • 1970-01-01
  • 2017-04-05
  • 2017-09-04
  • 1970-01-01
相关资源
最近更新 更多