Angular Virtual Scroll Not Detecting Changes to Add Items for Reactive FormArray












2















I am working with the new control in Angular 7 and cannot seem to get it to recognize that I've added a new item to the array that is being displayed.



Here is my html:



<cdk-virtual-scroll-viewport class="list-container lg" [itemSize]="52.5">
<div *cdkVirtualFor="let state of statesObservable | async;" class="list-group-item">
<div class="state">{{state.name}}</div>
<div class="capital">{{state.capital}}</div>
</div>
</cdk-virtual-scroll-viewport>


and here is the setup for the component:



import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Component({
selector: 'app-virtual-scroll',
templateUrl: './virtual-scroll.component.html',
styleUrls: ['./virtual-scroll.component.css']
})
export class VirtualScrollComponent {

states = [
{ name: 'Alabama', capital: 'Montgomery' },
{ name: 'Alaska', capital: 'Juneau' },
];
statesObservable = new BehaviorSubject(this.states);

sortBy(prop: 'name' | 'capital') {

// this works -- creates a new array
this.statesObservable.next(this.states.map(s => ({ ...s })).sort((a, b) => {
const aProp = a[prop], bProp = b[prop];
if (aProp < bProp) {
return -1;
} else if (aProp > bProp) {
return 1;
}
return 0;
}));
}

addItem() {
// this does not work
this.states.push({ name: 'Wyoming', capital: 'Cheyenne' });
this.statesObservable.next(this.states);
}

}


I've created a stackblitz of the issue (based on an existing stackblitz that I found):



https://stackblitz.com/edit/angular-material-wlrjys



The very weird thing is that if you recreate the array by using a map function, it works and and the newly added items appear.



I've traced the issue into the guts of core.js and it looks as if it's not seeing the change to the array when I call .next() on the BehaviorSubject.



Any help is appreciated --



UPDATE



Of course, 10 minutes after I post this (after two days of searching) I find (half) the answer I'm searching for. It looks like change detection is not picking this up because I'm not changing the variable itself, just adding to it. Which I understand. The question is, how do I get a new variable for an existing FormArray -- do I have to recreate the entire thing? Seems like overkill.










share|improve this question





























    2















    I am working with the new control in Angular 7 and cannot seem to get it to recognize that I've added a new item to the array that is being displayed.



    Here is my html:



    <cdk-virtual-scroll-viewport class="list-container lg" [itemSize]="52.5">
    <div *cdkVirtualFor="let state of statesObservable | async;" class="list-group-item">
    <div class="state">{{state.name}}</div>
    <div class="capital">{{state.capital}}</div>
    </div>
    </cdk-virtual-scroll-viewport>


    and here is the setup for the component:



    import { Component, OnInit } from '@angular/core';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject';

    @Component({
    selector: 'app-virtual-scroll',
    templateUrl: './virtual-scroll.component.html',
    styleUrls: ['./virtual-scroll.component.css']
    })
    export class VirtualScrollComponent {

    states = [
    { name: 'Alabama', capital: 'Montgomery' },
    { name: 'Alaska', capital: 'Juneau' },
    ];
    statesObservable = new BehaviorSubject(this.states);

    sortBy(prop: 'name' | 'capital') {

    // this works -- creates a new array
    this.statesObservable.next(this.states.map(s => ({ ...s })).sort((a, b) => {
    const aProp = a[prop], bProp = b[prop];
    if (aProp < bProp) {
    return -1;
    } else if (aProp > bProp) {
    return 1;
    }
    return 0;
    }));
    }

    addItem() {
    // this does not work
    this.states.push({ name: 'Wyoming', capital: 'Cheyenne' });
    this.statesObservable.next(this.states);
    }

    }


    I've created a stackblitz of the issue (based on an existing stackblitz that I found):



    https://stackblitz.com/edit/angular-material-wlrjys



    The very weird thing is that if you recreate the array by using a map function, it works and and the newly added items appear.



    I've traced the issue into the guts of core.js and it looks as if it's not seeing the change to the array when I call .next() on the BehaviorSubject.



    Any help is appreciated --



    UPDATE



    Of course, 10 minutes after I post this (after two days of searching) I find (half) the answer I'm searching for. It looks like change detection is not picking this up because I'm not changing the variable itself, just adding to it. Which I understand. The question is, how do I get a new variable for an existing FormArray -- do I have to recreate the entire thing? Seems like overkill.










    share|improve this question



























      2












      2








      2


      1






      I am working with the new control in Angular 7 and cannot seem to get it to recognize that I've added a new item to the array that is being displayed.



      Here is my html:



      <cdk-virtual-scroll-viewport class="list-container lg" [itemSize]="52.5">
      <div *cdkVirtualFor="let state of statesObservable | async;" class="list-group-item">
      <div class="state">{{state.name}}</div>
      <div class="capital">{{state.capital}}</div>
      </div>
      </cdk-virtual-scroll-viewport>


      and here is the setup for the component:



      import { Component, OnInit } from '@angular/core';
      import { BehaviorSubject } from 'rxjs/BehaviorSubject';

      @Component({
      selector: 'app-virtual-scroll',
      templateUrl: './virtual-scroll.component.html',
      styleUrls: ['./virtual-scroll.component.css']
      })
      export class VirtualScrollComponent {

      states = [
      { name: 'Alabama', capital: 'Montgomery' },
      { name: 'Alaska', capital: 'Juneau' },
      ];
      statesObservable = new BehaviorSubject(this.states);

      sortBy(prop: 'name' | 'capital') {

      // this works -- creates a new array
      this.statesObservable.next(this.states.map(s => ({ ...s })).sort((a, b) => {
      const aProp = a[prop], bProp = b[prop];
      if (aProp < bProp) {
      return -1;
      } else if (aProp > bProp) {
      return 1;
      }
      return 0;
      }));
      }

      addItem() {
      // this does not work
      this.states.push({ name: 'Wyoming', capital: 'Cheyenne' });
      this.statesObservable.next(this.states);
      }

      }


      I've created a stackblitz of the issue (based on an existing stackblitz that I found):



      https://stackblitz.com/edit/angular-material-wlrjys



      The very weird thing is that if you recreate the array by using a map function, it works and and the newly added items appear.



      I've traced the issue into the guts of core.js and it looks as if it's not seeing the change to the array when I call .next() on the BehaviorSubject.



      Any help is appreciated --



      UPDATE



      Of course, 10 minutes after I post this (after two days of searching) I find (half) the answer I'm searching for. It looks like change detection is not picking this up because I'm not changing the variable itself, just adding to it. Which I understand. The question is, how do I get a new variable for an existing FormArray -- do I have to recreate the entire thing? Seems like overkill.










      share|improve this question
















      I am working with the new control in Angular 7 and cannot seem to get it to recognize that I've added a new item to the array that is being displayed.



      Here is my html:



      <cdk-virtual-scroll-viewport class="list-container lg" [itemSize]="52.5">
      <div *cdkVirtualFor="let state of statesObservable | async;" class="list-group-item">
      <div class="state">{{state.name}}</div>
      <div class="capital">{{state.capital}}</div>
      </div>
      </cdk-virtual-scroll-viewport>


      and here is the setup for the component:



      import { Component, OnInit } from '@angular/core';
      import { BehaviorSubject } from 'rxjs/BehaviorSubject';

      @Component({
      selector: 'app-virtual-scroll',
      templateUrl: './virtual-scroll.component.html',
      styleUrls: ['./virtual-scroll.component.css']
      })
      export class VirtualScrollComponent {

      states = [
      { name: 'Alabama', capital: 'Montgomery' },
      { name: 'Alaska', capital: 'Juneau' },
      ];
      statesObservable = new BehaviorSubject(this.states);

      sortBy(prop: 'name' | 'capital') {

      // this works -- creates a new array
      this.statesObservable.next(this.states.map(s => ({ ...s })).sort((a, b) => {
      const aProp = a[prop], bProp = b[prop];
      if (aProp < bProp) {
      return -1;
      } else if (aProp > bProp) {
      return 1;
      }
      return 0;
      }));
      }

      addItem() {
      // this does not work
      this.states.push({ name: 'Wyoming', capital: 'Cheyenne' });
      this.statesObservable.next(this.states);
      }

      }


      I've created a stackblitz of the issue (based on an existing stackblitz that I found):



      https://stackblitz.com/edit/angular-material-wlrjys



      The very weird thing is that if you recreate the array by using a map function, it works and and the newly added items appear.



      I've traced the issue into the guts of core.js and it looks as if it's not seeing the change to the array when I call .next() on the BehaviorSubject.



      Any help is appreciated --



      UPDATE



      Of course, 10 minutes after I post this (after two days of searching) I find (half) the answer I'm searching for. It looks like change detection is not picking this up because I'm not changing the variable itself, just adding to it. Which I understand. The question is, how do I get a new variable for an existing FormArray -- do I have to recreate the entire thing? Seems like overkill.







      angular angular-material2 angular7 angular-cdk






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 '18 at 15:50







      John Azzolina

















      asked Nov 23 '18 at 15:35









      John AzzolinaJohn Azzolina

      487




      487
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449413%2fangular-virtual-scroll-not-detecting-changes-to-add-items-for-reactive-formarray%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449413%2fangular-virtual-scroll-not-detecting-changes-to-add-items-for-reactive-formarray%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'