Louis
Louis

Reputation: 2608

two way binding of iterable in ngFor

I am using ngFor to create a list of items containing clickable icons.
When I click on an icon, it calls a function to update a variable in the backend and when successful, I'd like the icon to change color.

How can I "two-way" bind the iteratable variable obj so that when I modify it in the controller it reflects in the template ?

Template:

<ion-item *ngFor="let obj of contactList | separator  " 
(click)="show_memories(obj.key, obj.bookName)" class="task-snoozed" no-lines>
    <button ion-button icon-only clear 
   (click)="$event.stopPropagation(); sendChangeState(obj, 'toBe', obj.toBeAlerted)">
        <ion-icon name="arrow-dropleft-circle" size="large" 
        [color]="obj.toBeAlerted ? 'primary' : 'gray-light'"></ion-icon>
    </button>

</ion-item>

Controller:

sendChangeState(contact:any, alertType:string, bool:boolean){

    this.firestoreService.changeAlertState(this.userId, contact.key, alertType, bool)
    .then(() => {
        //update the icon color here:
        contact.toBeAlerted = !contact.toBeAlerted; 
    });     
}

EDIT contactList is an object like this: enter image description here

Upvotes: 0

Views: 163

Answers (2)

Louis
Louis

Reputation: 2608

This does the job:

 <ion-item *ngFor="let obj of contactList | separator; index as i;" (click)="show_memories(obj.key, obj.bookName)" class="task-snoozed" no-lines>

    <button ion-button icon-only clear (click)="$event.stopPropagation(); sendChangeState(obj, 'toBe', !obj.toBeAlerted)">
        <ion-icon name="arrow-dropleft-circle" size="large" [color]="contactList[obj.key].toBeAlerted ? 'primary' : 'gray-light'"></ion-icon>
    </button>

</ion-item>

Upvotes: 0

Sneha Pawar
Sneha Pawar

Reputation: 1127

When you bind single CSS property using property binding always use style.property-name as follows:

Use [style.color] instead of [color]

Replace below line

[color]="obj.toBeAlerted ? 'primary' : 'gray-light'"

with

[style.color]="obj.toBeAlerted ? 'primary' : 'gray-light'"

You can also use ngStyle to apply css conditionally as follows

[ngStyle]="{'color': "obj.toBeAlerted ? 'primary' : 'gray-light'"}"

Upvotes: 5

Related Questions