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
650 views
in Technique[技术] by (71.8m points)

click event not working from dynamically generated HTML angular 2

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
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

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

...