2

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?

1

2 Answers 2

1

Try this

      do(event, index, item) {
          this.result.splice(index, 0, 'Hi!');
      }
Sign up to request clarification or add additional context in comments.

Comments

0

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>');

    }
}

1 Comment

how to do this for multiple spans? for example spans generated by NgFor. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.