1

I want to load a jquery script in Angular 4. In the html I have a table which display some data :

<table class="table">
    <thead class="thead-inverse">
    <tr>
        <th>#</th>
        <th>Hotel name</th>
        <th>Price for night</th>
        <th>Address</th>
        <th>Action</th>
    </tr>
    </thead>
    <tbody>
        <tr *ngFor="let hotel of hotels">
            <td>{{hotel.id}}</td>
            <td>{{hotel.name}}</td>
            <td>{{hotel.pricePerNight}}</td>
            <td>{{hotel.address.city}}{{hotel.address.country}}</td>                                
        </tr>
    </tbody>
</table>

And I want to use a jquery script to allow me to change some data when I click in some td.

And this my component.ts :

 @Component({
  selector: 'hotel',
  templateUrl: './hotel.component.html'
})
export class HotelComponent implements OnInit {

  data: any;

  constructor(){
    this.getData((data) => {
      this.data = data;
    });
   }
  ngOnInit() { }
  ngAfterViewInit() {
    $('td').on('click', function() {
      console.log("alooo");
      var $this = $(this);
      var $input = $('<input>', {
          value: $this.text(),
          type: 'text',
          blur: function() {
             $this.text(this.value);
          },
          keyup: function(e) {
             if (e.which === 13) $input.blur();
          }
      }).appendTo( $this.empty() ).focus();
    });
  }
  public getData(data) {
    const req = new XMLHttpRequest();
    req.open('GET', 'assets/data/listOfHotels.json');
    req.onload = () => {
      data(JSON.parse(req.response));
    };
    req.send();
  }
}

The data displayed perfectly but when I click in any column I get nothing. (I made a simple code with and ... a static table, it works but in the dynamic version it doesn't work) Any help !

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
S.Akrem
  • 71
  • 10
  • 1
    using jquery and angular same time is not recommended, previously I tried that and not worked as expected, please select one those. – artgb Nov 10 '17 at 10:33
  • 1
    The issue is because the `td` elements are not present in the DOM when you try and attach the event handler to them. You need to use a delegated event handler instead. ***However***, the bigger issue is that you shouldn't be using jQuery and Angular together. Use the methods that Angular exposes to hook events to dynamic content, and remove jQuery completely. – Rory McCrossan Nov 10 '17 at 10:34
  • You are mixing up things here. With angular2, you better use `(click)` directive in your HTML along with a function defined in your component's constructor. Take a look at [**ng-click in angular2** article](http://www.angulartutorial.net/2016/07/ng-click-in-angular-js-2.html) for further details. – cнŝdk Nov 10 '17 at 10:39

0 Answers0