0

I have an Angular chat app that allows a user to fabricate chats. The app takes input, processes the input text when the submit button is clicked, refreshes with ngInit so the chats new message is displayed. However the input field continues to hold the previous message input. I want the input to be empty/clear every time the submit button is clicked.

    <input #taskTitleInput class="input has-background-light is-medium" type="text"
    placeholder="Enter message..."><br>
    (click)="createLeftMessage(taskTitleInput.value)">Alice</button>

And here is the component function that adds the message to the chat.

  createLeftMessage(title: string) {
    if (typeof this.chatId === "string") {
      this.chatService.createMessage(title, this.chatId, true).subscribe((newMessage: any) => {
        console.log("added message to chat");
        this.ngOnInit();
      })
  }
  }

I have tried the following in the createLeftMessage function, but it does not recognize taskTitleInput.

taskTitleInput.value == '';

How can I have the input field cleared automatically every time the submit button is clicked?

2 Answers 2

1

Please use ngModel directive, bind some component class property with your input text and reset the property upon button click. Something like this

<input type="text" [(ngModel)]="text1" />
<button (click)="clickMe()">Click Me</button>

In the .ts file, you will have something like

public text1:string = "";
public clickMe():void
{
  console.log(this.text1); //do whatever with the bound property
  this.text1 = ""; //and reset the property afterwards.
}

Please find StackBlitz

Thanks.

Sign up to request clarification or add additional context in comments.

1 Comment

Also I wouldn't call ngOnInit() from your component code. This is a method that Angular calls to let you know your component has been created and initialized. If you do want to call code that's in ngOnInit() move it into a separate method and call it from ngOnInit(). This will save you pain later on.
1

You would have to use @ViewChild() in your typescript file.

<input #taskTitleInput type="text" placeholder="Enter message...">
<button (click)="createLeftMessage(taskTitleInput.value)">Alice</button>

TS:

@ViewChild('firstNameInput') nameInputRef: ElementRef;
...
show(){
     console.log('-*-*-*',this.nameInputRef.nativeElement.value );
      var newName = this.nameInputRef.nativeElement.value;
      alert(newName);
      this.nameInputRef.nativeElement.value = '';
}

I added a stackblitz for you:

https://stackblitz.com/edit/angular-template-reference-variable-r2grmr?file=src%2Fapp%2Fapp.component.ts

Comments

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.