Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

javascript - Angular2 and jQuery 'change' events

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)'>

Then in my case, I have to use jQuery to change value of this input, then trigger change event:

$('#input1').val('somevalue').trigger('change');

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');
})

In angular2 component:

//This is not working
onChange(): void{
  console.log('Change made');
}

How can I work around in this situation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Demo plunker here.

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');
  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...