typescripthashmapangular6ng-switchangularjs-ng-switch

How to use ngSwitch with *ngFor in Angular 6


I have a Map as follows with dynamic keys and values

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

Key value pairs will be as follows (other dynamic values may present)

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

To display this data in HTML, I used the following code

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

And the above code gives me an output as follows

enter image description here

But I need to disable the fields lat and lon using ngSwitch. So that I can get an output as follows

enter image description here


Solution

  • Finally I could find a solution after repeated reading the Angular Documents.

    The following code solved my issue :

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

    I have used the <ul> tag for looping the data within my Map. That is, featureData. The looped data has been passed to the Switch. As I have to use disabled for known keys lat, lon and data, I kept them in cases and left all others in Default Case.

    The (change) function at Default Case was called for my particular usecase and is not related to this question.