0

I am working on an angular application. In HTML of a component within mat-select I am trying to remove whiteapces using .trim() method but my application is breaking. My code

<div class="col-2">
    <mat-form-field>
            <mat-select
                    placeholder="Source"
                    [(ngModel)]="applicable.SourceNm.trim()">
                    <mat-option
                            *ngFor="let source of applicableLevel.SourceListTxt.split(',')"
                            [value]="source">
                            {{source.trim()}}
                    </mat-option>
            </mat-select>
    </mat-form-field>
</div>

If I remove the .trim() in ngModel, then the application is working fine. I am not sure what is wrong in using .trim() in ngModel. The error I get is

Parser Error: Unexpected token '=' at column 32 in [applicableLevel.SourceNm.trim()=$event] in ng:///AdminModule/ConfigurationComponent.html@516:160 ("                                                                                                    [ERROR ->][(ngModel)]="applicableLevel.SourceNm.trim()"

1 Answer 1

2

Demo You can try pipe for trimming

 import { Pipe, PipeTransform } from '@angular/core';
   @Pipe({
      name: 'trim',
      pure: false
   })
    
   export class TrimPipe implements PipeTransform {
      transform(value: string): any { 
        return value.trim()
      }
      
    }

in html {{source | trim }}

dont forget to add app.modules declarations this pipe.

ngModel assings to parameter not to function. So you need to delete trim() from ngModel and make your value as trimmed

<div class="col-2">
    <mat-form-field>
            <mat-select
                    placeholder="Source"
                    [(ngModel)]="applicable.SourceNm">
                    <mat-option
                            *ngFor="let source of applicableLevel.SourceListTxt.split(',')"
                            [value]="source | trim">
                            {{source | trim }}
                    </mat-option>
            </mat-select>
    </mat-form-field>
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

in code you didn't also closed mat-select after ngModel.
in ngmodel dont use trim you need to assing to parameter not to trim function. make your value as trimmed then your model value will be trimmed. I edited answer. Check demo in answer please
this way, I think I can trim values in applicableLevel.SourceListTxt, but I want to trim applicable.SourceNm. The initial value of applicable.SourceNm has white spaces. and this value is one among the dropdown. I think I have to do that in .ts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.