Artin Falahi
Artin Falahi

Reputation: 1151

Access to elementRef in click event in Angular

I defined string list in Component and it's rendering in view like this:

<span  class="one" (click)='do($event, index, item)' 
*ngFor="let item of result;let index = index"  >{{item}} </span>

After each item clicked I want to add div element after that item:

clickedSpan.insertAdjacentHTML('beforeend', '<div >Hi!</div>');

How can I access to elementRef in do function? Or Are there other solutions to manipulate rendered spans which rendered by ngFor?

Upvotes: 2

Views: 7420

Answers (2)

Balaji B
Balaji B

Reputation: 339

I template you can create one variable like "#addDivElement" in span tag

You can access these variable in component by using

@ViewChild('addDivElement') and you can do render the HTML element as you want 

import { Component, ViewChild, ElementRef, Renderer} from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: '/app/angular/app.angular.core.html'
})
export class AppComponent {

    @ViewChild('addDivElement')
    public addElement: ElementRef;

    public constructor(private rendere: Renderer) {

    }

    public arrayData = ["Item1", "Item2", "Item3"];

    public doSomething(event, index, item) {
        this.addElement.nativeElement.insertAdjacentHTML('beforeend', '<div class="two">two</div>');

    }
}

Upvotes: 0

Dmitrij Kuba
Dmitrij Kuba

Reputation: 1038

Try this

      do(event, index, item) {
          this.result.splice(index, 0, 'Hi!');
      }

Upvotes: 1

Related Questions