3
votes

I want to implement a like button (like in instagram, twitter etc) in my nativescript angular 2 app. clicking on the label should add the "active" class to the label. After clicking it again, it should remove the "active" class.

home.component.html

<label text="{{ post.likes }}" class="" (tap)="like()">

home.component.html (after clicking the label)

<label text="{{ post.likes }}" class="active" (tap)="like()>

home.component.ts

like() {
    if (/* post contains "active" class */) {
        // remove "active" class to label
    } else {
        // add "active" class to label
    }
}
2
Make sure you use Label with uppercase L - Narendra

2 Answers

0
votes

You need to use ngClass here.

<Label text="{{ post.likes }}" [ngClass]="liked ? 'active' : ''" (tap)="like()></Label>

and in your home.component.ts

like() {
//toggle this.liked here.
}
-1
votes

You can use the variable which store if it liked or not. Accordingly, it will add the class or remove the class from the element Example:

@Component({
    selector: 'app-element',
    template: '<div [class.liked]="post.liked">Hello Post <button (tap)="toggleLiked(post)"></button> </div>',
    styles: [`
       .liked {
           color: red
       }
    `]

})
export class AppComponent {
    liked = false;
    toggleLiked(post): void {
       post.liked = !post.liked;
    }
}

Note: Works because object referance. Example: https://stackblitz.com/edit/angular-mkravu?file=src%2Fapp%2Fapp.component.html