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;}
1

3 Answers 3

16

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

<p [style.z-index]="1">
  Some text
</p>
Sign up to request clarification or add additional context in comments.

1 Comment

I'm a C# developer trying to learn this stuff - not arguing with what you are saying but...why might your example be better?
11

You can use NgStyle directive for set zindex

[ngStyle]="{'z-index':condition ? 9 : 0 }"

Comments

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!

5 Comments

By typscript...not inline
The above code is not inline, Its binding! We have written css classes (You can place it accordingly).
I would say manipulating the DOM is not correct approach. Try utilizing the Angular features max.
gettign error:Property 'style' does not exist on type 'Element'. any

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.