首页 > 解决方案 > 角 | 在其他按钮上运行事件

问题描述

(无效问题,不需要参考,谢谢。)

解决方案:使用公共变量而不是 $event。


我想在其他按钮上运行该事件。

我使用$event,但我不能立即调用函数。


.html

<p-fileUpload (onSelect)="runSelect($event)"
    accept="image/*" #imageUpload></p-fileUpload>

<button (click)="callImageSelect()" #button2></button>

当 button2 被按下时,我想在#imageUpload 上运行 (onSelect) 事件。

(onSelect) 有一个参数。(event.files:选定文件列表)

如果按 button1 运行,

我想把默认值放在 $event 中。

所以我发现的方法是使用viewChild.


.ts

@ViewChild('imageUpload') imageUpload;

...
callImageSelect() {
    this.imageUpload.**onSelect()**;   // In this section, call (onSelect).
}

runSelect(event) {
     event.files.push(defalut);
     // Here I put the default value for event.
}

有什么好办法吗?

感谢您的意见。

标签: htmlangulartypescriptevent-handling

解决方案


你想要的是触发事件onSelect。这里要注意的一点onSelect不是 a functionbut event。您不应该调用实际触发它的event调用。function

由于您使用onSelect的是自定义事件,因此您必须使用一些Directive相同的事件。所以你应该做的是,访问组件内部的指令并调用触发事件的函数(EventEmitter);

Sue-do 代码

@Directive(selector="my-directive")
public class MyDirective {

 value : string;

 onSelect = new EventEmitter();

 public selectionMade(){
      this.onSelect.emit(value);
 }

}

组件 html

<button (onSelect)="runSelect($event)" myDirective #myDirective="myDirective"></button>

<button (click)="clickTest()" #button2></button>

组件 ts

@ViewChild('myDirective') myDirective : MyDirective;

...
clickTest() {
    this.myDirective.selectionMade();   // In this section, call (onSelect).
}

推荐阅读