3

I have one mat-select dropdown and one input field. When the button is clicked it submits data. After data is submitted I want to clear the input field but I don't want to clear the mat-select dropdown. How can I do that?

chat.component.html

<div>
  <mat-form-field>
    <mat-select placeholder="Select User" [(ngModel)]="userObject.userid" 
      name="userid" required>
      <mat-option *ngFor="let userObj of userObj [value]="userObj.userid">
        {{userObj.username}}
      </mat-option>
    </mat-select>
  </mat-form-field>  

  <mat-form-field>
    <input matInput placeholder="Type Message" [(ngModel)]="userObject.chatmessage">
  </mat-form-field>

  <button mat-raised-button color="primary" (click)="sendMessage()">
    SEND MESSAGE</button>
</div>
3
  • Try userObject.chatmessage = ''; A better way would be to just use a ReactiveForm and then call the reset method on it. Commented Oct 8, 2018 at 7:34
  • Where i have to put this ? Commented Oct 8, 2018 at 7:35
  • In your Component Class. Commented Oct 8, 2018 at 7:35

4 Answers 4

3

Since you're two-way data binding to userObject.chatmessage, just setting it to an empty string in your component will do the trick.

In your ChatComponent TypeScript class, just do this:

sendMessage() {
  // After Sending Message
  userObject.chatmessage = '';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Glad it helped.
If you get the value of input field with $event you can do this (event.target as HTMLInputElement).value = ' ';
3

I think you should use Reactive forms and call reset()-method on the form.

You can also manually reset the form fields as suggested above by SiddAjmera.

Comments

0

I think the Reactive form is the best way to do it, https://angular.io/guide/reactive-forms use this link to do it reset the input field by assigning the empty string is not the way to do that, it will going to give error in some condition

Comments

0

I think the way to do this while using Reactive form protocols is upon your button click is to .setValue('').

So instead your send message would look like this.

sendMessage() {
   // Operations here prior to resetting value...
   this.userObjectField.setValue('');
}

Comments

Your Answer

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