Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click event not working from dynamically generated HTML angular 2

Tags:

angular

I am creating tables rows when the http.get method updates me ... on receiving data I create table rows using JS / jquery in the angular 2 version.

My Code:

<tr>
    <td>2</td>
    <td>BAJAJ-AUTO</td>
    <td>14.284%</td>
    <td>27/12/2013 12:00 am</td>
    <td>30/12/2013 12:00 am</td>
    <td>1935</td>
    <td>30/12/2013 12:00 am</td>
    <td>1935</td>
    <td>31/12/2013 12:00 am</td>
    <td>2120</td>
    <td><button class="btn btn-default" onclick="processAdvise('BAJAJ-AUTO')">Process Advise</button></td>
</tr>

so the last the td - has a button which shall call my angular 2 function to process it - This code doesnt reaches even at the start of the function

I also tried this to no avail:

  • (click) for angular 2
  • onclick and kept the function in the same HTML template using script tag
like image 724
Abdeali Chandanwala Avatar asked Mar 25 '26 09:03

Abdeali Chandanwala


1 Answers

Angular2 doesn't process HTML outside of a components template in any way, therefore it is expected (click)="processAdvise('BAJAJ-AUTO') doesn't work.

onclick="processAdvise('BAJAJ-AUTO')" also won't work when processAdvise() is a method of an Angular2 component because onclick is HTML-only and functions assigned this way are searched in the global JS scope not inside a components class.

<script> tags are remove from Angular2 templates

@Component({
  selector: '...',
  ....
})
class MyComponent {
  constructor(private elRef:ElementRef) {
  }

  addHtml() {
    // add the HTML to the DOM
    this.elRef.nativeElement.querySelector('button').addEventListener('click', (event) => this.handleClick(event));
  }

  handleClick(event) {
    // doSomething();
  }
}
like image 191
Günter Zöchbauer Avatar answered Mar 27 '26 01:03

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!