skip to Main Content

I don’t know why, when I interact with my textarea, my _messagesList is reverse ASC and DESC everytime.

        <div class="chat__messages">
            <div *ngFor="let message of authService._messagesList.reverse()" [@fadeInOut] class="message" [ngClass]="session.User.id == message.Id_Sender ? 'myMsg' : 'otherMsg'">
                <p>{{message.Content}}</p>
                <span>{{message.createdAt | date: "HH:mm"}}</span>
            </div>
            <span class="loader" *ngIf="isLoading"></span>
        </div>
        <div class="chat__send">
            <textarea #textarea (input)="adjustTextareaHeight()" rows="1" [(ngModel)]="_content" (keydown.enter)="sendMessage();$event.preventDefault()" placeholder="Envoyer un message"></textarea>
            <button (click)="sendMessage()"><svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 512 512"><path d="M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"/></svg></button>
        </div>

Edit : that work with "authService._messagesList.slice().reverse()" but I don’t now why.
If someone can explain to me

2

Answers


  1. The reverse method does not work in the template
    Reverse the array in the logic code and just pass the array to ngFor

    Login or Signup to reply.
  2. You are calling methods in your angular template which is very taxing on your change detection cycle so I would really recommend against that. Like, REALLY recommend against it.

    Now, the reason it reverses is because of the above protest. Every time change detection runs, it executes the reverse method. Reverse isn’t like slice or anything that returns a NEW array. Reverse flips the array IN PLACE and returns a reference to the original array, meaning the array in the service gets flipped. When change detection calls that method 5-10 times back to back to back, you will see it flip back and forth on you. That’s one of the big reasons I recommended NEVER using methods in your template. Change detection will run them dozens of times over and it severely impacts the performance of your renderer. Try creating a getter for that array that console.logs the value every time it is retrieved and you will see what I mean.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search