angular - 来自带有 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>
whereorg4
和org5
只是另外两个选择元素。
如果我希望根据我通过代码所做的事情来调用该方法(例如手动更改选择的值)我应该以某种方式“触发”该事件,还是我的代码应该只是手动调用该onOrg3Change
方法,因为我已经得到对选择元素的引用?
解决方案
值更改后,您需要手动触发事件。Angular 不知道任何 html 元素值的值是否从代码中更改(这意味着不是通过交互)
您可以通过以下方式发出事件:
@ViewChild('org3') org3: ElementRef;
this.org3.nativeElement.value = 'two';
this.org3.nativeElement.dispatchEvent(new Event('change'));
看这个简单的演示
推荐阅读
- javascript - 从 Vuejs 数据表中删除行
- html - 如何在 TripAdvisor 中使用 Puppeteer.js (node.js) 获取动态 Html 标签的内部文本?
- function - 尝试从 PowerShell 中的函数传回字符串
- ionic-framework - 创建带有缩略图、按钮和可点击行的离子列表
- laravel - LARAVEL - 在验证之前修改数据库数据
- javascript - 这种 cookie 验证安全吗?
- amazon-web-services - EC2 中有问题的 AWS CLI - 无法连接到 EndPoint
- c - 是否有一种算法可以打印数组子序列的所有排列?
- php - laravel - 如何在使用多个中间件时从第一个中间件返回响应
- c++ - 为什么 c++ 中的组合数据结构比独立数组的性能低