Fixing your solution
Some problems with your code were already mentioned in other answers. Another thing to remind you of is the way you modify the eating property: You have to make sure to replace the array with a new array, each time an entry changes. Else the Change Detector will not pick up your changes.
You could do it like this:
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' // Map the entry if it matches your condition
? {...entry, eating: 'Chocolate'} // If it does, create a new one with the altered eating property
: entry // If not, return the entry itself without modification
);
}
Here is a working Stackblitz.
Cleaner solution
Calling a function inside an expression binding is not a good practice in Angular, since the Change Detector will have to rerun those methods each time there might have been a change. A cleaner way is to either hold a variable and change it accordingly (reactive apporach) or use a pipe.
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' // Map the entry if it matches your condition
? {...entry, eating: 'Chocolate'} // If it does, create a new one with the altered eating property
: entry // If not, return the entry itself without 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 is equal to food
}
}
Again, another working Stackblitz.
myarrayContainsEatingdo?if (myarray[i].eating === "Chocolate") { ... }. Also, your currentmyarraydoesn't have any object with the eating key whose value is chocolate.