Vahid Najafi
Vahid Najafi

Reputation: 5243

Angular add class to component from component css file

I want to add a class to my component when I click a button. So I do it with Renderer2 as following:

this.renderer.addClass(this.elRef.nativeElement, 'photo-removing');

The class only applies when I add the css class in a global css file. It doesn't work when I add it to the component css file. Any idea why does this happen?

Update: Here is my component html:

<div *ngIf="imgMainUrl">
    <img
        [src]="imgMainUrl"
        [style.width.px]="width" [style.height.px]="height"
        [ngClass]="{ 'img-radius' : rounded }"
    >
    <i
        [pTooltip]="tooltipTxt" [tooltipPosition]="tooltipPosition"
        class="icon-close close-btn"
        (click)="removePhoto()">
    </i>
</div>

And css:

.photo-removing {
    opacity: 0.4;
    border:1px solid red;
}

Upvotes: 1

Views: 2769

Answers (3)

Manzer A
Manzer A

Reputation: 3816

Try:-

Stackblitz Link:- https://stackblitz.com/edit/renderer2-example-2-wdz4og?file=src/app/app.component.css

.html

<div #test *ngIf="imgMainUrl">
  test
    <img
        [src]="imgMainUrl"
        [style.width.px]="width" [style.height.px]="height"
        [ngClass]="{ 'img-radius' : rounded }"
    >
<button type="button" (click)="addClass()">asasas</button>

</div>

.ts

  @ViewChild('test') test: ElementRef;
  imgMainUrl = true;
  constructor(private renderer: Renderer2) { }
  addClass() {
    this.renderer.addClass(this.test.nativeElement, 'photo-removing');
  }

Upvotes: 1

c__money
c__money

Reputation: 76

This is a perfect example of when to use [ngClass] directive.

If you're simply using the button to toggle some variable, you can do this...

In your component.ts file:

public clicked: boolean = false;

click() {
     this.clicked ? false : true;
}

In your component.html file:

<button (click)="click()">Set to {{!clicked}}</button>

<div [ngClass]="{'your-class' : clicked}"></div>

If you really want to use a renderer, the you need to set this code in your angular app:

encapsulation: ViewEncapsulation.None.

By setting this value to None, you are telling Angular not to encapsulate your views. That way, the default scoping rules, isolations, and protections for styling won't apply. So, Angular adds the CSS to the global styles. This is essentially the same as pasting the component's styles into the HTML.

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

Upvotes: 1

Falyoun
Falyoun

Reputation: 3966

You can use [ngClass] with *ngIf instead

In .html:

<button (click)="buttonClicked()"></button>

<div [ngClass]={checker === true ? 'photo-removing' : ''}></div>

And in .ts file:

export class Home{

  checker:boolean = false;
  constructor(){}


  buttonClicked() {
   this.checker = !this.checker;
  }
}

Upvotes: 1

Related Questions