0

This is the closest question I could find to what I'm asking but they manually apply the index and have multiple elements while I do not.

Is there a way to change the specific element's class in the component?

html

here I get the id from the clicked item just fine, but I change the class on click, completing a task. When I click the complete button, all tasks in the loop return completed. I'm not sure how to use i here effectively because onclick I'm also sending a put request so I can't add more info to the function without also sending to the database where I don't need it...

<tr *ngFor="let task of tasks; let i = index;">

<button mat-button
            class="btn"
            [ngClass]="status ? 'btn-lemon-complete' : 'btn-lemon'"
            [disabled]="status ? true : false"
            (click)="completeTask(task._id)"
            >{{ status ? 'Completed' : 'Complete Task' }}</button>

            <button mat-button
            class="btn delete"
            *ngIf="status"
            >✘</button>

component

completeTask(taskId, data): any {
    this.status = true;
    this.triggerService.updateTask(taskId, data).subscribe(res => {
    });

    let item = taskId;
    let index = this.tasks.indexOf(taskId);
    console.log(item, index, this.tasks);
}

console.log(item, index, this.tasks); returns id, -1, [0{task here}1{task here}]

I think I'm getting the -1 because the actual _id field is in position -1 of the single task I click.

How can I achieve what I'm trying to? Thanks.

2 Answers 2

1

You can try with this solution

component.html

<button mat-button
    class="btn"
    [ngClass]="task.status ? 'btn-lemon-complete' : 'btn-lemon' "
    [disabled]="task.status ? false : true"
    (click)="completeTask(task)"
>
{{ task.status ? 'Completed':'Complete Task' }}
</button>

component.ts

completeTask(task, data?): any {
    this.triggerService.updateTask(task._id, data).subscribe(res => {
    });
    task.status=true;
}

EDIT- Passed task from html, made second param optional

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, thank you!! I just learned how to bind it to the string instead, too since it was in my database as a string not a boolean. Very interesting!
0

You can try class binding:

[class.btn-lemon-complete]="status"

link to docs: https://angular.io/guide/template-syntax#class-binding

2 Comments

The class changes just fine this way though, I only want to change it for the task I clicked instead of ALL tasks
Add a property to that task and use that instead of status. toggle that property when clicking. toggle it back when done.

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.