Reputation: 1351
I am not able to change class when clicking on the button.
I am using this.
event.srcElement.classList.remove("unsubscribe");
event.srcElement.classList.add("subscribe");
I am passing the event in function when clicking on the button.
<a #subscribe title="unsubscribe" *ngIf="rec?.attributes?.Subscription == 'true'" class='unsubscribe' (click)="subscribeUnsubscribe($event);$event.stopPropagation();" data-toggle="modal"></a>
<a #subscribe title="subscribe" *ngIf="rec?.attributes?.Subscription == 'false' || rec?.attributes?.Subscription == null || rec?.attributes?.Subscription == 'undefined'" class='subscribe' (click)="subscribeUnsubscribe($event);$event.stopPropagation();" data-toggle="modal"></a>
The problem is I am having two angular components in one component the srcElement is working fine and toggling the classes, but in another component, it is not working and giving the below error.
ERROR TypeError: Cannot read property 'srcElement' of undefined
Upvotes: 0
Views: 432
Reputation: 53
Use ngClass to check all your conditions and return your style class. For example:
<a #subscribe [ngClass]="getstyleClass(rec)" title="unsubscribe" (click)="subscribeUnsubscribe($event);$event.stopPropagation();" data-toggle="modal"></a>
and in your component file
public getstyleClass(rec: any):string {
if (rec?.attributes?.Subscription === true){
return "unsubscribe";
}
if (rec?.attributes?.Subscription == 'false' || rec?.attributes?.Subscription == null || rec?.attributes?.Subscription == 'undefined') {
return "subscribe";
}
return "";
}
Upvotes: 0
Reputation: 349
I don't know the reason why it gives you an error, but this code is not enough to know really. Have you considered using the NgClass
directive? Here a tutorial
You can do something like this:
Component:
public subscribed: boolean;
Template:
<div #someElement [class.subscribe]="!subscribed" [class.unsubscribe]="subscribed"></div>
Upvotes: 1
Reputation: 983
Ok so you can do something like this:
subscribeUnsubscribe(event) {
event.srcElement.classList.remove("unsubscribe");
setTimeout(()=>{
event.srcElement.classList.add("subscribe");
},0)
}
I hope it helps.
Upvotes: 0