单击提交按钮后,Angular 将输入设置为空白

时间:2021-02-26 03:15:48

标签: angular

我有一个 Angular 聊天应用,允许用户编造聊天。该应用程序接受输入,在单击提交按钮时处理输入文本,使用 ngInit 刷新,以便显示聊天新消息。然而,输入字段继续保存先前的消息输入。我希望每次点击提交按钮时输入都为空/清除。

#include <algorithm>
#include <string>
#include <iostream>
#include <cctype>

std::string ToCamelCase(std::string str) noexcept {
    if(str.empty()) return {};
    for(auto iter = std::begin(str); iter != std::end(str) - 1; /* DO NOTHING */ ) {
        if(*iter == '-' || *iter == '_') {
            iter = str.erase(iter);
            *iter = static_cast<char>(std::toupper(*iter));
            continue;
        }
        ++iter;
    }
    return str;
}

这里是将消息添加到聊天中的组件函数。

std::transform

我在 createLeftMessage 函数中尝试了以下操作,但它无法识别 taskTitleInput。

<块引用>

taskTitleInput.value == '';

如何在每次点击提交按钮时自动清除输入字段?

2 个答案:

答案 0 :(得分:1)

请使用 ngModel 指令,将一些组件类属性与您的输入文本绑定,并在按钮点击时重置该属性。像这样

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

在 .ts 文件中,你会有类似的内容

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

请找到StackBlitz

谢谢。

答案 1 :(得分:1)

您必须在打字稿文件中使用 @ViewChild()

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

我为你添加了一个stackblitz:

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