我有一个隐藏的输入来控制jQuery所做的更改,其中包括angular2 更改的事件,就像这样
I have a hidden input to control the changes made by jQuery, which includes an event of angular2 change, like this
<input id='input1' hidden (change)='onChange($event)'>然后在我的情况下,我必须使用jQuery来改变此输入,然后触发更改事件:
Then in my case, I have to use jQuery to change value of this input, then trigger change event:
$('#input1').val('somevalue').trigger('change');我通过jQuery触发的更改事件仅适用于jQuery,但不适用于Angular2:
This change event that I triggered via jQuery only works with jQuery, but not Angular2:
//This is working $('#input').change(function(){ console.log('Change made'); })在angular2组件中:
In angular2 component:
//This is not working onChange(): void{ console.log('Change made'); }在这种情况下我该如何解决?
How can I work around in this situation?
推荐答案您可以将模板引用变量分配给< input> ,例如#hiddenInput1 ,在组件类中获取其原生元素(通过 @ViewChild ),然后使用jQuery本身来监听更改事件。
You could assign a template reference variable to the <input>, like #hiddenInput1, get a hold of its native element (via @ViewChild) inside the component class and then use jQuery itself to listen to the change event.
演示plunker 此处。
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>My First Angular 2 App</h1> <hr> <input id='input1' hidden #hiddenInput1> ` }) export class AppComponent implements AfterViewInit { @ViewChild('hiddenInput1') hiddenInput1:ElementRef; ngAfterViewInit() { $(this.hiddenInput1.nativeElement).on('change', (e) => { console.log('Change made -- ngAfterViewInit'); this.onChange(e); }); } onChange(): void{ console.log('Change made -- onChange'); } }更多推荐
Angular2和jQuery'改变'事件
发布评论