1

I have a pie chart that I have hidden by default as such:

 .sub-chart {
    min-height: 300px;
    width: 100%;
    margin-bottom: 24px;
    visibility: hidden;
 }

However, upon a user filtering on a different chart, I want to change the css visibility attribute so that the chart is no longer hidden.

How am I able to update css via the typescript component file?

1
  • 1
    you can use <div class="sub-chart" [style.visibility]="condition?'visible':null">` and make the condition true/false. As style has priority over class, you see the "div" Commented May 12, 2020 at 15:59

2 Answers 2

1

Demo create attribute

isDivVisible="visible"

in html give as its style

<div class="sub-chart" [style.visibility]="isDivVisible"></div>

in component change isDivVisible like below

this.isDivVisible="hidden";
Sign up to request clarification or add additional context in comments.

1 Comment

This works, but it would arguably be better to swap a css class in and out instead of directly tweaking the style in code. You can bind to [ngClass] to do this. See angular.io/api/common/NgClass
1

You can do it using ViewChild decorator and Renderer2 service like so:

1) In the component template add a template variable:

<my-element #myElement></my-element>

2) In the ts file:

@ViewChild('myElement') myElement: ElementRef<any> // the argument type can be HTMLElement / HTMLDivElement / component etc.

constructor(private renderer: Renderer2) {}

myMethod() {
 this.renderer.setStyle(this.myElement.nativeElement, 'visibility', 'visible');
}

ViewChild, Renderer2, ElementRef must be imported from @angular/core.

You can also use addClass and/or removeClass methods instead of setStyle for the renderer.

If you are using Angular 8 you need to pass a configuration object as a second argument to the @ViewChild like so: @ViewChild('myElement', { static: false }). The static property must be set to true if it is used in OnInit life cycle hook (for Angular 9 as well).

Comments

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.