Improving your code solution
In addition to the feedback provided in previous responses, it's important to highlight a key aspect when modifying the eating
property: make sure to replace the array with a new one each time a change is made. Otherwise, the Change Detector won't detect the modifications.
A recommended approach would be:
Template
<div *ngIf="myarrayContainsEating('Chocolate')">Chocolate Is Good</div>
<button (click)="charlesEatChoc()">Make Charles eat Chocolate</button>
TS
myarray = [{'name':'Charles', 'age':25, 'eating':'Vanilla'}, {'name':'Joseph', 'age':18, 'eating':'Banana'}]
myarrayContainsEating(food) {
return this.myarray.some(entry => entry.eating === food); // Check if any "eating" property is equal to food
}
charlesEatChoc() {
this.myarray = this.myarray.map(entry => // This returns a new array (!!!IMPORTANT!!!)
entry.name === 'Charles'
? {...entry, eating: 'Chocolate'} // If match, create a modified entry
: entry // Return unmodified entry
);
}
Here is a live Stackblitz example.
Better coding practice
Embedding functions within expression bindings in Angular isn't ideal as it can impact performance by causing reevaluation of methods on potential changes. A cleaner approach involves using variables or employing pipes.
Component Template
<div *ngIf="myarray | containsFood:'Chocolate'">Chocolate Is Good</div>
<button (click)="charlesEatChoc()">Make Charles eat Chocolate</button>
Component TS
myarray = [{'name':'Charles', 'age':25, 'eating':'Vanilla'}, {'name':'Joseph', 'age':18, 'eating':'Banana'}]
charlesEatChoc() {
this.myarray = this.myarray.map(entry => // This returns a new array (!!!IMPORTANT!!!)
entry.name === 'Charles'
? {...entry, eating: 'Chocolate'} // Modify entry if condition met
: entry // No modification
);
}
Pipe TS
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'containsFood'
})
export class ContainsFoodPipe implements PipeTransform {
transform(value: Array<any>, food:string): boolean {
return value.some(entry => entry.eating === food); // Check if any "eating" property matches food
}
}
Another working Stackblitz demo can be accessed for reference.