chink
chink

Reputation: 1653

Not able remove white spaces in HTML of a component in Angular application using .trim() method

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()"

Upvotes: 0

Views: 4009

Answers (1)

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17610

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>

Upvotes: 2

Related Questions