-1

code :

platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {

  if (window['ngRef']) {
    window['ngRef'].destroy();
  }
  window['ngRef'] = ref;

 
}).catch(err => console.error(err));

the above code form main.ts file from angular. how to fix in this case? what is the correct way to update this code?

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

2

Change it to any type

const _window = window as any;
if (_window['ngRef']) {
  _window.destroy();
}
_window['ngRef'] = ref;

The above code is used by webpack for hot reloads to ensure Angular destroys itself on hot reloads.

Read about the typescript error here

BTW if you don't want to use any, but want to use strict type instead, then you can extend window's type

//This will tell typescript that window also contains ngRef property
type windowExtended = Window & typeof globalThis & {
  ngRef: NgModuleRef<AppModule>;
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .then(ref => {
    const _window = window as windowExtended;
    if (_window['ngRef']) {
      _window['ngRef'].destroy();
    }
    _window['ngRef'] = ref;

  })
Sameer
  • 4,758
  • 3
  • 20
  • 41
  • If window['ngRef'] doesn't exist because ngModule wasn't injected, there is no sense to do, if will never validate – Vega Jul 28 '22 at 18:42
0

I've given a spin to Sameer answer.

type WindowExtended = Window & typeof globalThis & {
  ngRef: ApplicationRef;
}

bootstrapApplication(AppComponent)
  .then((ref: ApplicationRef) => ensureDestroyOnHotReload(ref))
  .catch((err) => console.error(err));

function ensureDestroyOnHotReload(ref: ApplicationRef): void {
  let { ngRef } = window as WindowExtended
  if (ngRef) {
    ngRef.destroy()
  }
  ngRef = ref
}
mpalliser
  • 41
  • 4