【发布时间】:2019-10-09 00:56:30
【问题描述】:
我的 app.component.html 文件中列出了一个表单,如下所示,当我单击“发送”按钮提交表单时,我的 Javascript 中出现错误,提示 chatForm 未定义。
我查看了一些不同的教程,但我似乎无法找到为什么此功能没有按预期运行。我究竟做错了什么?
另外,当我提交表单时,如何获取表单中存在的输入值?我在表单上定义了一个名称message,我该如何使用这个变量?
app.component.html
<div class="container">
<h2>Message Form</h2>
<form (ngSubmit)="sendMessage(chatForm)" #chatForm="ngForm">
<div>
<label for="message">Message</label>
<input type="text" id="message" name="message" [(ngModel)]="message" required>
</div>
<button type="submit" id="sendmessage" [disabled]="!chatForm.valid">
Send
</button>
</form>
</div>
app.component.ts
public sendMessage(form): void {
console.log("Message sent: " + form.value);
}
【问题讨论】:
-
你在 app.component.ts 中定义了
@ViewChild('chatForm') form吗? -
@Viqas 我没有,应该在哪里定义?
-
无需使用ViewChild
标签: javascript angular typescript single-page-application angular8