Trim the field value and set the value in onchange event angular

664 views Asked by At

I need to trim the field value and set the value in onchange event angular

<form [formGroup]="form" (ngSubmit)="submitForm()">
<div>
<input type="text" matInput formControlName="name" [(ngModel)]="name" (ngModelChange)="mychange($event)">
</div>
</form>

private mychange(event) {
       console.log(event) 
       let name: any
        let c = event.trim();
        console.log(c);
    }

Please let me know anybody have idea

1

There are 1 answers

0
Connect2sky On

You can use value changes event to detect changes, and you can subscribe to that to detect changes.

.html code

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-md-offset-2 col-sm-offset-1">
      <form [formGroup]="form">
        <div formGroupName="userData">
          <div class="form-group">
             <label for="username">UserName</label>
             <input type="text" class="form-control"
              id="username" formControlName = "username" (change)="onSubmit()">
          </div>
        </div>
        <button class="btn btn-primary" type="submit">Submit</button> 
      </form>
    </div>
  </div>
</div>

.ts code

export class AppComponent implements OnInit {
  form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      userData: new FormGroup({
        username: new FormControl(null, [Validators.required])
      })
    });
  }

  onSubmit() {
    this.form.get("userData").valueChanges.subscribe(val => {
      console.log(val.username.trim());
    });
  }
}