首页 > 解决方案 > 来自带有 ViewChild 的代码的 Angular 5 触发事件

问题描述

在 Angular 中是否可以通过 typescript 中的方法触发 HTML 中定义的更改事件?

我正在通过 ViewChild 获取我的选择器。

@ViewChild('org3') org3Selector: HTMLSelectElement;

并且该元素有一个change事件集:

<select class="form-control" id="orgLevel3" name="orgLevel3" #org3
        (change)="onOrg3Change($event.target.value, org4, org5)">
    <option>-- Select --</option>
    <option *ngFor="let name of validOrgLevel3" value="{{name.id}}">
        {{name.name}}
    </option>
</select>

whereorg4org5只是另外两个选择元素。

如果我希望根据我通过代码所做的事情来调用该方法(例如手动更改选择的值)我应该以某种方式“触发”该事件,还是我的代码应该只是手动调用该onOrg3Change方法,因为我已经得到对选择元素的引用?

标签: angularangular5viewchild

解决方案


值更改后,您需要手动触发事件。Angular 不知道任何 html 元素值的值是否从代码中更改(这意味着不是通过交互)

您可以通过以下方式发出事件:

@ViewChild('org3') org3: ElementRef;

this.org3.nativeElement.value = 'two';
this.org3.nativeElement.dispatchEvent(new Event('change'));

看这个简单的演示


推荐阅读