【问题标题】:How to use ngSwitch with *ngFor in Angular 6如何在 Angular 6 中将 ngSwitch 与 *ngFor 一起使用
【发布时间】:2020-04-20 18:56:07
【问题描述】:

我有一个带有动态键和值的 Map,如下所示

public featureData = new Map<string, string>();

键值对如下(可能存在其他动态值)

[
  {"name" : "Bangalore"},
  {"type" : "city"},
  {"lat" : "12.9716"},
  {"lon" : "77.5946"}
]

为了在 HTML 中显示这些数据,我使用了以下代码

<div class="modal-body">
 <div class="form-group">
  <h4>
   <ol>
    <li *ngFor="let feature of this.featureData | keyvalue"> {{ feature.key }} : <input type="text" class="custom-field form-control form-control-sm form-control form-control-sm-sm"  (change)="updateAnyHashMap(this.featureData, feature.key, $event.target.value)" autocomplete="off" value="{{ feature.value }}"> </li>
   </ol>
  </h4>
 </div>
</div>

上面的代码给了我如下输出

但我需要使用 ngSwitch 禁用字段 latlon。这样我就可以得到如下输出

【问题讨论】:

  • 到目前为止,您尝试过什么来解决这个问题?
  • 这里不知道怎么用ngswitch。为了满足我的用例,根据我的理解,ngswitch 是唯一的解决方案

标签: typescript hashmap angular6 ng-switch angularjs-ng-switch


【解决方案1】:

我不明白你为什么要使用ngSwitch,而你可以使用disabled 属性来做到这一点。我不认为你可以使用ngSwitch 是这种情况

由于我们没有什么可比较的,所以我直接比较关键值

将您的 input 更改为

<input type="text" class="custom-field form-control form-control-sm form-control form-control-sm-sm"  (change)="updateAnyHashMap(this.featureData, feature.key, $event.target.value)" autocomplete="off" value="{{ feature.value }}" [disabled]="feature.key === 'lat' || feature.key === 'lon'">

长话短说,我添加了以下属性

[disabled]="feature.key === 'lat' || feature.key === 'lon'"

【讨论】:

    【解决方案2】:

    反复阅读Angular Documents终于找到了解决办法。

    以下代码解决了我的问题:

    <ul *ngFor="let feature of this.featureData | keyvalue" [ngSwitch]="feature.key">
      <li *ngSwitchCase="'lat'"> {{ feature.key }} : <input type="text" class="custom-field form-control form-control-sm form-control form-control-sm-sm" value="{{ feature.value }}" disabled>
      </li>
    
      <li *ngSwitchCase="'lon'"> {{ feature.key }} : <input type="text" class="custom-field form-control form-control-sm form-control form-control-sm-sm" value="{{ feature.value }}" disabled>
      </li>
    
      <li *ngSwitchCase="'data'"> {{ feature.key }} : <input type="text" class="custom-field form-control form-control-sm form-control form-control-sm-sm" value="{{ feature.value }}" disabled>
      </li>
    
      <li *ngSwitchDefault> {{ feature.key }} : <input type="text" class="custom-field form-control form-control-sm form-control form-control-sm-sm" (change)="updateAnyHashMap(this.featureData, feature.key, $event.target.value)" autocomplete="off" value="{{ feature.value }}">
      </li>
    </ul>
    

    我使用了&lt;ul&gt; 标签来循环我的Map 中的数据。即featureData。循环数据已传递给Switch。由于我必须使用 disabled 来获取已知的密钥 lat、lon 和数据,因此我将它们保存在 cases 中,而将所有其他密钥保留在 Default Case 中。

    Default Case(change) 函数是针对我的特定用例调用的,与此问题无关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-17
      • 2023-04-03
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2018-11-09
      相关资源
      最近更新 更多