ViewContainerRef with ResizeObserver doesn't work properly in angular2019 Community Moderator ElectionAngular HTML bindingHow to detect a route change in Angular?Angular EXCEPTION: No provider for HttpAngular - Set headers for every requestWhat is the equivalent of ngShow and ngHide in Angular?Angular/RxJs When should I unsubscribe from `Subscription`Huge number of files generated for every Angular projectAngular 5 - Remove DOM Elements, View Won't RefreshError: StaticInjectorError(AppModule)[NgIf -> ViewContainerRef]: After upgrading angular 6 to 7Angular 7 HttpClient response type as class

Averaging over columns while ignoring zero entries

A running toilet that stops itself

Why does this boat have a landing pad? (SpaceX's GO Searcher) Any plans for propulsive capsule landings?

Trigger on Custom Object Share

What can I do if someone tampers with my SSH public key?

What is the best index strategy or query SELECT when performing a search/lookup BETWEEN IP address (IPv4 and IPv6) ranges?

Is "cogitate" used appropriately in "I cogitate that success relies on hard work"?

Should I file my taxes? No income, unemployed, but paid 2k in student loan interest

Why isn't P and P/poly trivially the same?

How to recover against Snake as a heavyweight character?

What is better: yes / no radio, or simple checkbox?

What does *dead* mean in *What do you mean, dead?*?

Can inspiration allow the Rogue to make a Sneak Attack?

If nine coins are tossed, what is the probability that the number of heads is even?

Giving a talk in my old university, how prominently should I tell students my salary?

An Undercover Army

Tool for measuring readability of English text

Short story about an infectious indestructible metal bar?

How do property taxes on school district bonds work?

How to distinguish easily different soldier of ww2?

Vector-transposing function

Unfamiliar notation in Diabelli's "Duet in D" for piano

Does the US political system, in principle, allow for a no-party system?

Is the differential, dp, exact or not?



ViewContainerRef with ResizeObserver doesn't work properly in angular



2019 Community Moderator ElectionAngular HTML bindingHow to detect a route change in Angular?Angular EXCEPTION: No provider for HttpAngular - Set headers for every requestWhat is the equivalent of ngShow and ngHide in Angular?Angular/RxJs When should I unsubscribe from `Subscription`Huge number of files generated for every Angular projectAngular 5 - Remove DOM Elements, View Won't RefreshError: StaticInjectorError(AppModule)[NgIf -> ViewContainerRef]: After upgrading angular 6 to 7Angular 7 HttpClient response type as class










0















I am trying to add and remove components dynamically depending on the the screen size using ComponentFactoryResolver.



@ViewChild('sidebarContainer', read: ViewContainerRef ) sidebarContainer: ViewContainerRef;

_handleBodyResize() {
let self = this;
if (typeof ResizeObserver == 'undefined') return;

const obs = new ResizeObserver(entries =>
let entry = entries[0];

if ((entry.contentRect.width) < MOBILE_WIDTH)
if (this.deviceType !== DeviceType.mobile)
this.removeSidebar();

this.deviceType = DeviceType.mobile;

else
if (this.deviceType !== DeviceType.desktop)
this.addSidebar();

this.deviceType = DeviceType.desktop;

;
);

removeSidebar()
this.sidebarContainer.clear();
this.sidebarRef.destroy();


addSidebar()
this.sidebarContainer.clear();
//_cfr is componentFactoryResolver
const compFactory = this._cfr.resolveComponentFactory(this.array[0]);

let comp = this.sidebarContainer.createComponent(compFactory);

this.sidebarRef = comp;



and the HTML



<div class="sidebar-container">
<div #sidebarContainer>

</div>




This sidebarContainer viewContainerRef can't seem to hold on to the references and creates new instance of the SidebarComponent whenever the with of the body goes from < 768px to >= 768px and doesn't delete the previously created component saved in sidebarRef and event the sidebarContainer.clear() method doesn't work



Strangely if I use window.addEventListener('resize'... it works.



Is there some underlying ResizeObserver technicality that I am not aware of and is there a way to make it work with ResizeObserver



Update



I forgot to mention this, but the code inside the resize observer executes on time and calls both of the functions appropriately.



The else section always creates a new instance of the SidebarComponent and renders it into view but this.sidebarContainer.clear() and this.sidebarRef.destroy don't remove the previously created instances even though while debugging, I can see that sidebarContainer and sidebarRef are not undefined and are relevant instances of ViewContainerRef and ComponentRef respectively.










share|improve this question




























    0















    I am trying to add and remove components dynamically depending on the the screen size using ComponentFactoryResolver.



    @ViewChild('sidebarContainer', read: ViewContainerRef ) sidebarContainer: ViewContainerRef;

    _handleBodyResize() {
    let self = this;
    if (typeof ResizeObserver == 'undefined') return;

    const obs = new ResizeObserver(entries =>
    let entry = entries[0];

    if ((entry.contentRect.width) < MOBILE_WIDTH)
    if (this.deviceType !== DeviceType.mobile)
    this.removeSidebar();

    this.deviceType = DeviceType.mobile;

    else
    if (this.deviceType !== DeviceType.desktop)
    this.addSidebar();

    this.deviceType = DeviceType.desktop;

    ;
    );

    removeSidebar()
    this.sidebarContainer.clear();
    this.sidebarRef.destroy();


    addSidebar()
    this.sidebarContainer.clear();
    //_cfr is componentFactoryResolver
    const compFactory = this._cfr.resolveComponentFactory(this.array[0]);

    let comp = this.sidebarContainer.createComponent(compFactory);

    this.sidebarRef = comp;



    and the HTML



    <div class="sidebar-container">
    <div #sidebarContainer>

    </div>




    This sidebarContainer viewContainerRef can't seem to hold on to the references and creates new instance of the SidebarComponent whenever the with of the body goes from < 768px to >= 768px and doesn't delete the previously created component saved in sidebarRef and event the sidebarContainer.clear() method doesn't work



    Strangely if I use window.addEventListener('resize'... it works.



    Is there some underlying ResizeObserver technicality that I am not aware of and is there a way to make it work with ResizeObserver



    Update



    I forgot to mention this, but the code inside the resize observer executes on time and calls both of the functions appropriately.



    The else section always creates a new instance of the SidebarComponent and renders it into view but this.sidebarContainer.clear() and this.sidebarRef.destroy don't remove the previously created instances even though while debugging, I can see that sidebarContainer and sidebarRef are not undefined and are relevant instances of ViewContainerRef and ComponentRef respectively.










    share|improve this question


























      0












      0








      0








      I am trying to add and remove components dynamically depending on the the screen size using ComponentFactoryResolver.



      @ViewChild('sidebarContainer', read: ViewContainerRef ) sidebarContainer: ViewContainerRef;

      _handleBodyResize() {
      let self = this;
      if (typeof ResizeObserver == 'undefined') return;

      const obs = new ResizeObserver(entries =>
      let entry = entries[0];

      if ((entry.contentRect.width) < MOBILE_WIDTH)
      if (this.deviceType !== DeviceType.mobile)
      this.removeSidebar();

      this.deviceType = DeviceType.mobile;

      else
      if (this.deviceType !== DeviceType.desktop)
      this.addSidebar();

      this.deviceType = DeviceType.desktop;

      ;
      );

      removeSidebar()
      this.sidebarContainer.clear();
      this.sidebarRef.destroy();


      addSidebar()
      this.sidebarContainer.clear();
      //_cfr is componentFactoryResolver
      const compFactory = this._cfr.resolveComponentFactory(this.array[0]);

      let comp = this.sidebarContainer.createComponent(compFactory);

      this.sidebarRef = comp;



      and the HTML



      <div class="sidebar-container">
      <div #sidebarContainer>

      </div>




      This sidebarContainer viewContainerRef can't seem to hold on to the references and creates new instance of the SidebarComponent whenever the with of the body goes from < 768px to >= 768px and doesn't delete the previously created component saved in sidebarRef and event the sidebarContainer.clear() method doesn't work



      Strangely if I use window.addEventListener('resize'... it works.



      Is there some underlying ResizeObserver technicality that I am not aware of and is there a way to make it work with ResizeObserver



      Update



      I forgot to mention this, but the code inside the resize observer executes on time and calls both of the functions appropriately.



      The else section always creates a new instance of the SidebarComponent and renders it into view but this.sidebarContainer.clear() and this.sidebarRef.destroy don't remove the previously created instances even though while debugging, I can see that sidebarContainer and sidebarRef are not undefined and are relevant instances of ViewContainerRef and ComponentRef respectively.










      share|improve this question
















      I am trying to add and remove components dynamically depending on the the screen size using ComponentFactoryResolver.



      @ViewChild('sidebarContainer', read: ViewContainerRef ) sidebarContainer: ViewContainerRef;

      _handleBodyResize() {
      let self = this;
      if (typeof ResizeObserver == 'undefined') return;

      const obs = new ResizeObserver(entries =>
      let entry = entries[0];

      if ((entry.contentRect.width) < MOBILE_WIDTH)
      if (this.deviceType !== DeviceType.mobile)
      this.removeSidebar();

      this.deviceType = DeviceType.mobile;

      else
      if (this.deviceType !== DeviceType.desktop)
      this.addSidebar();

      this.deviceType = DeviceType.desktop;

      ;
      );

      removeSidebar()
      this.sidebarContainer.clear();
      this.sidebarRef.destroy();


      addSidebar()
      this.sidebarContainer.clear();
      //_cfr is componentFactoryResolver
      const compFactory = this._cfr.resolveComponentFactory(this.array[0]);

      let comp = this.sidebarContainer.createComponent(compFactory);

      this.sidebarRef = comp;



      and the HTML



      <div class="sidebar-container">
      <div #sidebarContainer>

      </div>




      This sidebarContainer viewContainerRef can't seem to hold on to the references and creates new instance of the SidebarComponent whenever the with of the body goes from < 768px to >= 768px and doesn't delete the previously created component saved in sidebarRef and event the sidebarContainer.clear() method doesn't work



      Strangely if I use window.addEventListener('resize'... it works.



      Is there some underlying ResizeObserver technicality that I am not aware of and is there a way to make it work with ResizeObserver



      Update



      I forgot to mention this, but the code inside the resize observer executes on time and calls both of the functions appropriately.



      The else section always creates a new instance of the SidebarComponent and renders it into view but this.sidebarContainer.clear() and this.sidebarRef.destroy don't remove the previously created instances even though while debugging, I can see that sidebarContainer and sidebarRef are not undefined and are relevant instances of ViewContainerRef and ComponentRef respectively.







      angular angular7






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday







      Manish Singh

















      asked 2 days ago









      Manish SinghManish Singh

      124111




      124111






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Angular performs change detection in response to various triggers. DOM events, ajax requests, and timers/observables will trigger Angular's change detection.



          The window's resize event is an example of a DOM event that will trigger change detection.



          As far as I know, Angular's change detection is not automatically triggered by ResizeObserver. So you'll need to explicitly tell Angular to detect changes using ChangeDetectorRef.detectChanges():



          constructor(private changeDetector: ChangeDetectorRef) 

          ngAfterViewInit()
          const obs = new ResizeObserver(entries =>
          // Perform updates in response to resize

          // Then tell Angular to detect changes
          this.changeDetector.detectChanges();
          );
          obs.observe(this.resizeDiv.nativeElement);



          Here's a StackBlitz example.



          If you only care about changes to the viewport dimensions, there's no need to use ResizeObserver. The window resize event will work fine in all browsers.






          share|improve this answer























          • It worked after detectChanges(), please see my update on the question and can you please explain why this happened as the relevant functions were called properly, just the sidebarContainer.clear() function didn't gave any error and didn't do its job

            – Manish Singh
            yesterday










          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%2f55024086%2fviewcontainerref-with-resizeobserver-doesnt-work-properly-in-angular%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Angular performs change detection in response to various triggers. DOM events, ajax requests, and timers/observables will trigger Angular's change detection.



          The window's resize event is an example of a DOM event that will trigger change detection.



          As far as I know, Angular's change detection is not automatically triggered by ResizeObserver. So you'll need to explicitly tell Angular to detect changes using ChangeDetectorRef.detectChanges():



          constructor(private changeDetector: ChangeDetectorRef) 

          ngAfterViewInit()
          const obs = new ResizeObserver(entries =>
          // Perform updates in response to resize

          // Then tell Angular to detect changes
          this.changeDetector.detectChanges();
          );
          obs.observe(this.resizeDiv.nativeElement);



          Here's a StackBlitz example.



          If you only care about changes to the viewport dimensions, there's no need to use ResizeObserver. The window resize event will work fine in all browsers.






          share|improve this answer























          • It worked after detectChanges(), please see my update on the question and can you please explain why this happened as the relevant functions were called properly, just the sidebarContainer.clear() function didn't gave any error and didn't do its job

            – Manish Singh
            yesterday















          1














          Angular performs change detection in response to various triggers. DOM events, ajax requests, and timers/observables will trigger Angular's change detection.



          The window's resize event is an example of a DOM event that will trigger change detection.



          As far as I know, Angular's change detection is not automatically triggered by ResizeObserver. So you'll need to explicitly tell Angular to detect changes using ChangeDetectorRef.detectChanges():



          constructor(private changeDetector: ChangeDetectorRef) 

          ngAfterViewInit()
          const obs = new ResizeObserver(entries =>
          // Perform updates in response to resize

          // Then tell Angular to detect changes
          this.changeDetector.detectChanges();
          );
          obs.observe(this.resizeDiv.nativeElement);



          Here's a StackBlitz example.



          If you only care about changes to the viewport dimensions, there's no need to use ResizeObserver. The window resize event will work fine in all browsers.






          share|improve this answer























          • It worked after detectChanges(), please see my update on the question and can you please explain why this happened as the relevant functions were called properly, just the sidebarContainer.clear() function didn't gave any error and didn't do its job

            – Manish Singh
            yesterday













          1












          1








          1







          Angular performs change detection in response to various triggers. DOM events, ajax requests, and timers/observables will trigger Angular's change detection.



          The window's resize event is an example of a DOM event that will trigger change detection.



          As far as I know, Angular's change detection is not automatically triggered by ResizeObserver. So you'll need to explicitly tell Angular to detect changes using ChangeDetectorRef.detectChanges():



          constructor(private changeDetector: ChangeDetectorRef) 

          ngAfterViewInit()
          const obs = new ResizeObserver(entries =>
          // Perform updates in response to resize

          // Then tell Angular to detect changes
          this.changeDetector.detectChanges();
          );
          obs.observe(this.resizeDiv.nativeElement);



          Here's a StackBlitz example.



          If you only care about changes to the viewport dimensions, there's no need to use ResizeObserver. The window resize event will work fine in all browsers.






          share|improve this answer













          Angular performs change detection in response to various triggers. DOM events, ajax requests, and timers/observables will trigger Angular's change detection.



          The window's resize event is an example of a DOM event that will trigger change detection.



          As far as I know, Angular's change detection is not automatically triggered by ResizeObserver. So you'll need to explicitly tell Angular to detect changes using ChangeDetectorRef.detectChanges():



          constructor(private changeDetector: ChangeDetectorRef) 

          ngAfterViewInit()
          const obs = new ResizeObserver(entries =>
          // Perform updates in response to resize

          // Then tell Angular to detect changes
          this.changeDetector.detectChanges();
          );
          obs.observe(this.resizeDiv.nativeElement);



          Here's a StackBlitz example.



          If you only care about changes to the viewport dimensions, there's no need to use ResizeObserver. The window resize event will work fine in all browsers.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 2 days ago









          Alex KAlex K

          1,195610




          1,195610












          • It worked after detectChanges(), please see my update on the question and can you please explain why this happened as the relevant functions were called properly, just the sidebarContainer.clear() function didn't gave any error and didn't do its job

            – Manish Singh
            yesterday

















          • It worked after detectChanges(), please see my update on the question and can you please explain why this happened as the relevant functions were called properly, just the sidebarContainer.clear() function didn't gave any error and didn't do its job

            – Manish Singh
            yesterday
















          It worked after detectChanges(), please see my update on the question and can you please explain why this happened as the relevant functions were called properly, just the sidebarContainer.clear() function didn't gave any error and didn't do its job

          – Manish Singh
          yesterday





          It worked after detectChanges(), please see my update on the question and can you please explain why this happened as the relevant functions were called properly, just the sidebarContainer.clear() function didn't gave any error and didn't do its job

          – Manish Singh
          yesterday



















          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%2f55024086%2fviewcontainerref-with-resizeobserver-doesnt-work-properly-in-angular%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

          How to get text form Clipboard with JavaScript in Firefox 56?How to validate an email address in JavaScript?How do JavaScript closures work?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I copy to the clipboard in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

          Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

          List of MPs elected to the English parliament in 1640 (April) Contents List of constituencies and members See also Notes References Navigation menueNational Archives – The Glynde Place ArchivesCobbett's Parliamentary history of England, from the Norman Conquest in 1066 to the year 1803'Aldermen in Parliament', The Aldermen of the City of London: Temp. Henry III – 1912onepage&q&f&#61, false 229