CruelEngine
CruelEngine

Reputation: 2841

Dynamically append data inside <div> angular6

I have a template : <div class='somedata'></div> I want to append a list of <div> dynamically one after the other . Data i fetch using a shared service through a Subject .

For Example :

<div class='somedata'>
<div id='dynamicdata1'>some data</div>
<div id='dynamicdata2'>some data</div>
..
..
..
</div>

dynamicdata1 , dynamicdata2 etc arrive one after the other with some delay .

Initially i thought of using an ngFor to render the div, but everytime i push a data into the ngFor bound variable , the loop runs again due to angular's changeDetection .

Is there any way this can be solved without using *ngFor ?

I know there is a way using jQuery where we can use $(selector).append() but is there anyway this can be done in angular?

Thanks ,

Upvotes: 0

Views: 784

Answers (2)

user4676340
user4676340

Reputation:

Following my comment, here is an example of a custom trackBy function :

<div *ngFor="let x of y; trackBy: customTB"></div>


customTB(index, item) {
  return item.id;
}

If the value returned by your function doesn't change, then the items won't move from your view when it is updated. So by giving new items to your array, and by returning only their ID, you will append items to the arrat, without moving the others.

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86740

You can use innerHTML to append some data into HTML element as per your requirements.

Upvotes: 0

Related Questions