10

I am trying to set zindex for a class using typescript. But it is not working. If you have any idea, please share with me.

 ngOnInit() { (<HTMLElement>document.querySelector('.pagemode')).style.z-index = 1;}
RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
Apple Orange
  • 646
  • 5
  • 12
  • 27

3 Answers3

15

You might be better using inline style binding rather than using querySelector - depending on the situation

<p [style.z-index]="1">
  Some text
</p>
Drenai
  • 11,315
  • 9
  • 48
  • 82
  • I'm a C# developer trying to learn this stuff - not arguing with what you are saying but...why might your example be better? – Jon Vote Jun 26 '20 at 17:08
  • 2
    `document.querySelector` is bypassing all of Angular's template binding functionality – Drenai Jun 28 '20 at 17:16
11

You can use NgStyle directive for set zindex

[ngStyle]="{'z-index':condition ? 9 : 0 }"
Gurpreet Singh
  • 3,061
  • 5
  • 19
  • 36
0

You can use NgClass directive rather than manipulating the DOM.

In your Css/Scss file:

.class1 {
  z-index: -1;
}

.class2 {
   z-index: 1;
}

In your TS file:

YourBooleanVariableNameHere : boolean;
ngOnInit() {
    this.YourBooleanVariableNameHere = true;
}

In your Html file:

If your condition is met:

<some-element [ngClass]="{'class1 class2' : YourBooleanVariableNameHere }">...</some-element>

If your condition is not met: Note that there is ! symbol with the variable

<some-element [ngClass]="{'class1' : !YourBooleanVariableNameHere }">...</some-element>

Read Usage Notes for more examples. Refer here for more approaches.,

Or Alternatively you can try the same approach, which is not recommended!

Update:

ngOnInit() {
    document.getElementsByClassName("pagemode")[0].style.zIndex = 1;
}

Working example available here!

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80