1

I'm creating an element as follows:

let tmplt=``;
      for(let i=0;i<wht.length;i++){
        tmplt +=`<li title="${wht[i]}" style="color:#000">
          <span (click)="slctRmv($event)">×</span>${wht[i]}
          </li>`;
      }
      jQuery("#myId").prepend(tmplt);

It is appending to the myId but click event is not triggering as in template.

So is there solution for this in angular2.

Akhilesh Kumar
  • 9,085
  • 13
  • 57
  • 95

2 Answers2

2

Direct DOM manipulation should be avoided in Angular2.

You can get a reference to an anchor element like

@Component({
  selector: '...',
  template: `<div><span #myAnchor></span></div>`})
class MyComponent {
  @ViewChildren('myAnchor') myAnchor;

  constuctor(private renderer:Renderer) {}

  ngAfterViewInit() {
    // this.myAnchor.nativeElement.appendChild();
    this.renderer.invokeElementMethod(this.myAnchor, 'appendChild', []);
  }
}

or other methods HTML elements provide see [Node.appendChild()](https://developer.mozilla.org/de/docs/Web/API/Node/appendChild

But prefer the methods Renderer provides.

You can also use

<div><span [innerHTML]="someField"></div>

with

class MyComponent {
  someField:string = '<div>xxx</div>';
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    #myId is dynamically created so there is no #myId in my view initially – Akhilesh Kumar Apr 13 '16 at 11:45
  • 1
    `(click)="slctRmv($event)"` or any other kind of Angular binding syntax doesn't work in dynamically added HTML. Components or directives are not instantiated neither. You probably want [DynamicComponentLoader](https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html) – Günter Zöchbauer Apr 13 '16 at 11:47
  • yes, I also suspect so, but how to use it in my scenario? – Akhilesh Kumar Apr 13 '16 at 11:52
  • What is your scenario? This might work for you http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 – Günter Zöchbauer Apr 13 '16 at 12:16
0

You can include the likes of jquery, although it's not advised if your intention is to modify stuff in the view.

You could also build a lite version https://www.npmjs.com/package/jquery-lite.

a genuine use case might be an external library returning some html , and you need to internally do some DOM manipulation on the returned html and send it to another service. It can be quite time consuming writing vanilla JS for that.

Joel Davey
  • 2,363
  • 1
  • 21
  • 20