0

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 ,

2
  • If you use a custom trackBy function, you can use ngFor to append new divs to the list. Commented Jun 29, 2018 at 6:37
  • @trichetriche can you help me out with an example ? Commented Jun 29, 2018 at 6:40

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

<div> that has dynamic data is unknown until i get the data i.e i have no clue if i have <div id='dynamicdata1'> . so i have to use innerHtml and re render the whole <div class='somedata'> everytime a new data arriveswhich i want to avoid

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.