1

I have the following code:

<select  class="form-control" required>
   <option *ngFor="let car of cars" type="text">{{car.Name}}</option>
</select>

my problem is that i can get just a name, so *ngFor fails. is there a way in HTML to make a condition like. If not Javascript or Jquery

     //There are more than 1 option
if(options.length>1){<option *ngFor="let car of cars" type="text">{{car.Name}}</option>}

//There is only an option
    else {<option *ngIf="car" type="text">{{car.Name}}</option>}

Car

export class Car {
  id: String;
  name: [{
        brand: String,
    }
  }]
}

JSON returns an Array[] when there are more than one element. If not, it returns an Object{} so I can not use *ngFor

Solved The problem was in the back-end, and not in the front-end

bellotas
  • 2,349
  • 8
  • 29
  • 60

5 Answers5

1

You can use *ngIf directive like:

<select id="oneICO" class="form-control" required *ngIf="cars.length > 1">
   <option *ngFor="let car of cars">{{car.Name}}</option>
</select>

<input type="text" *ngIf="cars.length < 2">{{car.Name}}</input>
Laiso
  • 2,630
  • 3
  • 16
  • 32
0

Checking if a variable is an array in the template is sort of nasty How to check type of variable in ngIf in Angular2

It would be better to check if !(cars instanceof Array) and then turn it into an array in your javascript code.

hayden
  • 2,643
  • 17
  • 21
0

In html you can use ngif in angular2

 <div *ngIf="options.length>1">
    <option *ngFor="let car of cars" type="text">{{car.Name}}</option>
  </div>

or simple put the next code in html

<option *ngIf="options.length == 1 " type="text">{{car.Name}}</option>
Aman
  • 806
  • 2
  • 12
  • 38
0

cars is not a collection so you don't need any angular directives:

<select id="oneICO" class="form-control" required>
   <option>{{cars.Name}}</option>
</select>

In which case, rename cars to car so that it signifies a single item.

[It is a little pointless, though, have a select with only a single option.]


Note that an option does not have a type attribute.

Andy G
  • 19,232
  • 5
  • 47
  • 69
0

Your original code is fine. There's nothing wrong with it.

<select id="oneICO" class="form-control" required>
  <option *ngFor="let car of cars" type="text">{{car.Name}}</option>
</select>

If you have single car, make an array of single element and it will work just fine.

cars = ['Honda']

If you have multiple cars, you'll have something like this.

cars = ['Honda', 'Toyota', 'Mitsubishi']
Nabin Paudyal
  • 1,591
  • 8
  • 14