0

I have an Angular (v7) project and there is a comment list on a component as shown below. I list comments in an *ngFor loop and add new ones to the list. However I reload the list after adding a new comment and I think there is a better way i.e. appending the newly added comment by combining it with HTML that I have used with JavaScript before. But unfortunately I have not managed to define it (maybe due to the loop). Is it possible in Angular?

#comment-list.html:

<div *ngFor="let comment of comments">
    <div class="p-col"> {{ comment.UserName }} </div>
    <div class="p-col-12" [innerHTML]="comment.Body"></div>
</div>

I call the method below after adding a new comment:

#comment-list.ts:

listComments() {
    this.loading = true;
    service.listComments(this)
        .subscribe(data => {
            this.records = data.Data;
            this.loading = false;
        });
}

I think I should re-create an HTML list using newly added comment's data and append it to the list but how?

2
  • 3
    this.comments.push(myNewComment) or this.records.push(myNewComment)... wala Commented May 1, 2019 at 20:41
  • @IsaacVidrine Thanks a lot, it seems to be OK but I just need some modification out of the scope. Regards... Commented May 1, 2019 at 21:34

1 Answer 1

1

You can use the Spread operator to do that. Suppose you have defined the newComment object. To update the list in the view, just:

this.comments = [newComment, ...this.comments];

It will insert the newComment object at the first place of the list.

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

3 Comments

Thanks a lot, but push method seems to be easier to apply. Voted up ;)
@Willys I wouldnt recommend using push method. Using spread operator is safe than push and basically you create new array of comment without modify the old one
@NgôHùngPhúc this could easily be done with unshift as well, you don't need spread operator

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.