-1

i have an angular click event attached on span in my component's html

<span (click)="doWork($event)" > Something </span>

and in my component i want to perform some operation and than add a class to this span using renderer2's addClass method. I injected Renderer2 from constrctor and used it in function

doWork (e) {
  //some operations
  this.renderer.addClass( e.target, 'selected' );
}

but i am unable to attach class on span in this way, am i missing something?

Haris Jamil
  • 133
  • 1
  • 10
  • Can you reproduce your issue in a stackblitz ? I can't reproduce your issue, [it's working](https://stackblitz.com/edit/angular-kl5yal) – Florian Jul 22 '19 at 12:37

2 Answers2

1

you can do something like this.

<span (click)="doWork()" id="sp_id"> Something </span> // You can use a class if you wish

Then in your constructor do this:

constructor(private renderer2: Renderer2) {
}

doWork() {
   const span_id = this.renderer.selectRootElement('#sp_id');
   this.renderer.addClass(span_id, 'spclass'); // spclass is the name of the class
}

That will fix it.

1

An alternative implementation for your desired behavior is use ngClass and a flag for add/remove your custom class on clicked element directly in HTML.

HTML:

<span [ngClass]="classAddFlag ? 'spClass' : ''" (click)="doWork()" > Something </span>

Then in your doWork() function you only need to set properly the flag for show or hide your class.

TS:

// Set the flag as component variable
classAddFlag = false;

doWork (e) {
   //some operations
   this.classAddFlag = !this.classAddFlag;
}
Simo
  • 305
  • 2
  • 9