【问题标题】:conditions for select - HTML or Javascript/Jquery选择条件 - HTML 或 Javascript/Jquery
【发布时间】:2018-01-05 10:38:25
【问题描述】:

我有以下代码:

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

我的问题是我只能得到一个名字,所以*ngFor 失败了。 HTML 中是否有办法制作类似的条件。如果不是 JavascriptJquery

     //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>}

汽车

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

JSON 在有多个元素时返回Array[]。如果没有,它会返回一个Object{},所以我不能使用*ngFor

已解决 问题出在后端,而不是在前端

【问题讨论】:

  • 问题不清楚
  • 我已经编辑过了
  • 您的原始代码看起来不错。如果集合中只有一辆车,那么您只会显示一个名称。
  • 它是一个 JSON,如果它只是一个名称,它就不是一个数组,只是一个对象。所以我不能使用 ngFor
  • 那么你不需要任何角度指令,只需要{{cars.Name}}。如果cars 只代表一辆汽车,则将其命名为car

标签: html angular if-statement select


【解决方案1】:

您可以使用*ngIf 指令,例如:

<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>

【讨论】:

    【解决方案2】:

    检查一个变量是否是模板中的一个数组有点讨厌How to check type of variable in ngIf in Angular2

    最好检查一下!(cars instanceof Array),然后在你的javascript代码中把它变成一个数组。

    【讨论】:

      【解决方案3】:

      在 html 中你可以在 angular2 中使用 ngif

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

      或者简单地将下一段代码放在html中

      <option *ngIf="options.length == 1 " type="text">{{car.Name}}</option>
      

      【讨论】:

        【解决方案4】:

        cars 不是一个集合,所以你不需要任何角度指令:

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

        在这种情况下,将cars 重命名为car,使其表示单个项目。

        [不过,有一个select 和一个option 有点毫无意义。]


        请注意,option 没有 type 属性。

        【讨论】:

        • 我已经编辑了我的问题,因为我认为它不清楚
        【解决方案5】:

        您的原始代码很好。没有任何问题。

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

        如果你只有一辆车,制作一个由单个元素组成的数组就可以了。

        cars = ['Honda']
        

        如果你有多辆汽车,你就会有这样的东西。

        cars = ['Honda', 'Toyota', 'Mitsubishi']
        

        【讨论】:

        • 没有。问题是汽车并不总是一个数组[]。有时它只是一个对象{}
        猜你喜欢
        • 2012-02-08
        • 2012-03-19
        • 2017-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-09
        • 1970-01-01
        相关资源
        最近更新 更多