Search code examples
angulardropdownngmodel

Slice Pipe throwing trimmed string instead for original string in onChange of dropdown in angular


I want to trim string from object when length of string greater than 5 so i have used Slice pipe in HTML but while onChange event but it is passing trimmed value which is done by pipe instead of original one.

studentList = [{"StudentName":"RockAngelWatson", studentId: "1"},
              {"StudentName":"MiyaAngelWatson", studentId: "2"}] ;

onChange(event,name)
    {
      console.log("&&&&",name)
    }

<select class="form-control" (change)="onChange($event,action)"  triggers="hover" container="body" placement="bottom auto" 
[(ngModel)]="action">
  <option *ngFor="let action of studentList">
  {{action.StudentName.length > 5 ? (action.StudentName | slice:0:5)+'...':(action.StudentName)}}
  </option>
  </select>

Console name result is "RockA..." but i want full name not trimmed string on change method which is nothing but original string "RockAngelWatson".


Solution

  • The problem isn't directly related with SlicePipe much less with the Angular specifically, but with the fact that you didn't add the [value] binding to the <option> so the text within option is assumed as the value to be bound to [(ngModel)].

    The solution is pretty simple, add the [value] to the <option>:

    <option *ngFor="let action of studentList" [value]="action.StudentName">
    

    DEMO