Reputation: 8828
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 2onclick
and kept the function in the same HTML template using
script tagUpvotes: 3
Views: 8067
Reputation: 176
Here is a simple solution I tried and it worked. Assign your component object to Window object in the constructor like the following:
...
constructor(private elementRef: ElementRef, private emService: SomeService) {
Window["myComponent"] = this;}
onClickAJS(){alert('it works!')}
...
Then you can access members of the component from DOM onclick="Window.myComponent.onClickAJS()". Also, you can call it from the browser console like : Window.myComponent.onClickAJS(), should work as well. It is a hackish way. More appropriate way is to create a component for your generated HTML and load it at run time. Here is the article to get you started. dynamic components
Upvotes: 2
Reputation: 657308
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();
}
}
Upvotes: 6