user10411207
user10411207

Reputation:

How to clear input field after submitting data in angular?

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>

Upvotes: 3

Views: 24554

Answers (4)

Christian Matthew
Christian Matthew

Reputation: 4339

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('');
}

Upvotes: 0

Akash Gupta
Akash Gupta

Reputation: 34

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

Upvotes: 0

Mureke
Mureke

Reputation: 131

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.

Upvotes: 3

SiddAjmera
SiddAjmera

Reputation: 39432

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 = '';
}

Upvotes: 3

Related Questions