MarkMark
MarkMark

Reputation: 184

how to skip in ngFor if was true, or other ways (Angular)

I have a more theoretical question, in my app, I have a component that receives as @Input an array with objects, where can be(or not) one of three categories, that also divides into three types, so here are the main categories:

  1. car_def
  2. car_fyr
  3. car_spy

and also each of them can be with parts _mid or _low to show its priority

So arr can look like this:

[
  {id: 2, key: "car_def"},
  {id: 2, key: "car_def_low"},
  {id: 2, key: "car_fyr"},
  {id: 2, key: "car_fyr_mid"}
]
 OR
[
  {id: 2, key: "car_spy"},
  {id: 2, key: "car_def"},
  {id: 2, key: "car_fyr"},
  {id: 2, key: "car_fyr_mid"}
]...

And if I receive some category - I need to display it in the template, but only ONCE and the main name. And also near it should be an icon, for which I have another func, where need to pass a category, as a param. SO from example, it should be car_def, car_fyr, or car_spy, car_def, car_fyr.

As for now, I wrote a function in .ts

@Input cars;
ngOnInit(): void {
    this.isDisplayed(this.cars);
}
isDisplayed(arr) {
    let str = arr.map(car => car.key).join(' ');
    if (str.match('car_def')) {
      this.isDef = true;
    }
    if (str.match('car_fyr')) {
      this.isFyr = true;
    }
    if (str.match('car_spy')) {
      this.isSpy = true;
    }
  }

and in HTML I use *ngIf

<div #container>
  <div *ngIf="isDef">
    CAR_DEF <icon icon="{{displayIcon('car_def')}}"></icon>
  </div>
  <div *ngIf="isFyr">
    CAR_FYR <icon icon="{{displayIcon('car_fyr')}}"></icon>
  </div>
  <div *ngIf="isSpy">
    CAR_SPY <icon icon="{{displayIcon('car_spy')}}"></icon>
  </div>
</div>

SO, my question is, is there a better way to write it? I thought about *ngFor but don't know how to display category only once in this case...

Would be really grateful for any advice!

Upvotes: 1

Views: 336

Answers (1)

Kinglish
Kinglish

Reputation: 23664

This would simplify it a little - your HTML wouldn't need to update when you added more type categories...

@Input cars;
typeData: any
 
isDisplayed(arr) {
    let str = arr.map(car => car.key).join(' ');
    if (str.match('car_def')) {
      this.typeData = {typeName: "CAR_DEF", icon: this.displayIcon('car_def')};
    } else if (str.match('car_fyr')) {
      this.typeData = {typeName: "CAR_FYR", icon: this.displayIcon('car_fyr')};
    } else if (str.match('car_spy')) {
      this.typeData = {typeName: "CAR_SPY", icon: this.displayIcon('car_spy')};
    }
  }


<div #container>
  <div *ngIf="typeData.typeName">
    {{typeData.typeName}} <icon icon="{{typeData.icon}}"></icon>
  </div>
</div>

Upvotes: 1

Related Questions