-1

Want to manipulate style's display. Here is the template:

<div style="display: none" #myDiv />

Thought there are 2 ways to do it:

  1. directly

    if (1===1) this.myDiv.style.display = "block";

  2. via @ViewChild

    @ViewChild('myDiv', { static: false}) myDiv if (1===1) this.myDiv.style.display = "block";

none working.

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Jeb50
  • 6,272
  • 6
  • 49
  • 87
  • 1
    Did any answer work for you? If yes do consider accepting/upvoting them. [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Nicholas K Nov 25 '19 at 07:22

3 Answers3

3

You can use ElementRef for this as follows.

HTML

<div class="my-div" style="display: none" />

TS

export class MyComponent implements AfterViewInit  {

  myDiv;

  constructor(private elementRef:ElementRef) {}

  ngAfterViewInit() {

    this.myDiv = this.elementRef.nativeElement.querySelector('.my-div');
  }
}

Then you can change styles using myDiv variable as follows.

this.myDiv.style.display = 'block';

StackBlitz Demo.

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45
1

Use ngStyle:

<div [ngStyle]="{'display': flag ? 'block' : 'none'}">
    ...
</div>

where flag can correspond to any boolean variable based on your logic in the corresponding .ts file.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
1

You can use Renderer2 to set style as well, The prototype of setStyle is as following:

setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void

Parameters:

el: any,     The element for whcih you set the style.

style:  string,  The name of the style.

value:  any,      The new value for style.

flags   RendererStyleFlags2,  Flags for style variations. No flags are set by default.

So you have to avoid use of ElementRef because direct access to the dom is not good for security, it is not safe, You can instead use Renderer2 to set Style

Demo example:

https://stackblitz.com/edit/renderer2-example-2-oryw2m?file=src/app/app.component.ts

Code Example:

import { Component, Renderer2, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  @ViewChild('test') test: ElementRef;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    this.renderer.setStyle(this.test.nativeElement, 'backgroundColor', 'red');
    this.renderer.setStyle(this.test.nativeElement, 'color', 'white');
  }
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
  • thank you for the details, as you answered in another [post](https://stackoverflow.com/questions/50193146/ngstyle-vs-renderer2-what-should-i-use/50194596?noredirect=1#comment104292769_50194596), `[ngStyle]` is actually usinge `Renderer`, I'd go with the simpler `ngStyle`. – Jeb50 Nov 25 '19 at 17:27