This is an simple example, real problem is more complex.
cars: string[] = ['audi', 'opel', 'mazda'];
isAudi: boolean = false;
isOpel: boolean = false;
checkCar(car):void {
if(car == 'audi'){
this.isAudi = true;
}
}
<div *ngFor="let car of cars" (validationCheck)="checkCar(car)">
<p *ngIf="isAudi">Audi: {{car}}</p>
<p *ngIf="isOpel">Opel: {{car}}</p>
</div>
validationCheck
is directive that triggers function for every item in array.
This will output:
Audi: audi
Audi: opel
Audi: mazda
I want only to show:
Audi: audi
*ngIf="car == 'audi'"
is out of the question because of real complexity of object.
Ps. if you want to downvote a question, give me a good explanation why question does not show research effort or its unclear or not useful, thx
You're not on the right track.
The flag "isAudi" is bound to each car: each car is an audi or is not. So the flag should be in the car, not in the component. Or it should be computed from a car.
So, solution one:
<div *ngFor="let car of cars">
<p *ngIf="isAudi(car)">Audi: {{car}}</p>
<p *ngIf="isOpel(car)">Opel: {{car}}</p>
</div>
isAudi(car: string) {
return car === 'Audi';
}
isOpel(car: string) {
return car === 'Opel';
}
Second solution, if the above causes performance problem because isAudi() is really complex to compute (which I doubt), use objects, precompute isAudi
and isOpel
when you get the data, and store it with the car:
interface FlaggedCar {
car: string;
isAudi: boolean;
isOpel: boolean;
}
this.flaggedCars = cars.map(car => {
return {
car,
isAudi: this.isAudi(car),
isOpel: this.isOpel(car)
}
});
<div *ngFor="let flaggedCar of flaggedCars">
<p *ngIf="flaggedCar.isAudi">Audi: {{flaggedCar.car}}</p>
<p *ngIf="flaggedCar.isOpel">Opel: {{flaggedCar.car}}</p>
</div>
Of course, this supposes that a car is not modified and doesn't become an Opel. Or the flag must be recomputed each time the car changes (which makes this solution more complex).
But again, you probably don't need this complexity, because isAudi()
and isOpel()
are probably fast enough to be called from the view.