Home > Enterprise >  Setting a CSS Id property inside ngOnInit not working in the browser
Setting a CSS Id property inside ngOnInit not working in the browser

Time:02-19

I'm having a little issue with setting a property height.

In my ngOnInit method I have this code below. When I step through it I can see the value of the property change in the console, but there's no change on screen or in the debugger. I also tried running this inside AfterViewInit but that didn't seem to do anything as well.

FYI - If I create a button and trigger it manually on the page I can make the change, it just doesn't work inside ngOnInit.

Any any one tell me why or if I'm doing something incorrectly?

ngOnInit(): void {
  if (something) {
    document.getElementById('map-full').style.setProperty('height', 'calc(100vh - 57px)');
  } else {
    document.getElementById('map-full').style.setProperty('height', 'calc(100vh - 105px)');
  }
}
<div id="map-full">

CodePudding user response:

It does work as is: https://stackblitz.com/edit/angular-ivy-hupjkb?file=src/app/hello.component.ts

You can change the if on line 10 and observe the 'Start Editing..' text shift up and down when the 'map' div changes height.

But this is not the idiomatic way to achieve this in angular:

  • you should avoid interacting with document and retrieving or manipulating the DOM in this manner.
  • it is preferred to keep styling in CSS rather than inline

A more typical approach is to use CSS and class bindings:

Template:

<div id="map-full" [class.full-height]="fullHeight || null">Map</div>

Component class:

fullHeight = false;

Changing the value of fullHeight will apply or remove the class from the div, which will apply the relevant CSS.

Stackblitz: https://stackblitz.com/edit/angular-ivy-gw4x8d?file=src/app/hello2.component.ts

  • Related