Mystikal_KK44
Mystikal_KK44

Reputation: 41

How to add style to html element in typescript and angular

I am trying to set property flex-grow to element but its not working.

script:

(this.elementRef.nativeElement as HTMLElement).setAttribute(
      'style',
      'flex-grow:' + this.panel.width && this.panel.width.type === 1 ? '0' : '1'
    );

the final result:

<ev-panel class="ev-panel ng-star-inserted" style="0" ng-reflect-panel="[object Object]"></ev-panel>
<ev-panel class="ev-panel ng-star-inserted" style="0" ng-reflect-panel="[object Object]"></ev-panel>
<ev-panel class="ev-panel ng-star-inserted" style="1" ng-reflect-panel="[object Object]"></ev-panel>

looks like it works fine, but where is flex-grow? I am asking for help and understanding

Upvotes: 1

Views: 2525

Answers (3)

user5480425
user5480425

Reputation:

Try the Angular Renderer2, is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly. This is the recommended approach.

     constructor(private renderer: Renderer2, private el: ElementRef) {

     const flexGrowValue = + this.panel.width && this.panel.width.type === 1 ? '0' : '1';

     this.renderer.setStyle(this.el.nativeElement, 'flex-grow',flexGrowValue  )

   }

https://angular.io/api/core/Renderer2

Simple example : https://stackblitz.com/edit/angular-ivy-3wyy4g

Upvotes: 0

Poul Kruijt
Poul Kruijt

Reputation: 71961

Considering you are using angular, you just use @HostBinding:

export class PanelComponent {
  @HostBinding('style.flex-grow')
  get flexGrow(): string {
    return this.panel?.type === 1 ? '0' : '1'
  }
}

the reason your code is not working though, is because you are missing parentheses. The entire statement in front of the question mark is evaluated first, including the flex-grow string. To do it your way (not advisable) you should do it like this:

(this.elementRef.nativeElement as HTMLElement).setAttribute(
  'style',
  'flex-grow:' + (this.panel.width && this.panel.width.type === 1 ? '0' : '1')
);

and with the latest angular/typescript version, you can also use optional chaining:

(this.elementRef.nativeElement as HTMLElement).setAttribute(
  'style',
  `flex-grow: ${this.panel.width?.type === 1 ? '0' : '1'}`
);

but again, @HostBinding is the way to go, if you are using angular

Upvotes: 1

Mohit
Mohit

Reputation: 522

Can you try this,

((this.elementRef.nativeElement as HTMLElement).setAttribute(
      'style',
      `flex-grow: ${this.panel.width && this.panel.width.type === 1 ? 0 : 1}`
    );

Hope this will set the correct thing.

Upvotes: 0

Related Questions