angular - Angular 在更改时将 ngModel 传递给组件
问题描述
尝试将 ngModel 发送回组件 onchange 以使其显示在控制台上。
Html 文件:尝试在 log 方法的帮助下 console.log ngModel。
<form action="">
<div class="form-group">
<label for="firstname">First name</label>
<input type="text" id="firstName" name="firstName" #firstName = "ngModel"
(change)="log(ngModel)" ngModel
class="form-control"/>
</div>
<div class="form-group">
<label for="comment">Comment</label>
<textarea id="comment" cols="30" rows="10" class="formcontrol"></textarea>
</div>
<button class="btn btn-primary">Submit</button>
</form>
零件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form-contact',
templateUrl: './form-contact.component.html',
styleUrls: ['./form-contact.component.css']
})
export class FormContactComponent {
log(x){
console.log(x);
}
}
收到以下错误:
- 没有找到 exportAs 'ngModel' 的指令。(name="firstName" #firstName = "ngModel")
- “FormContactComponent”类型上不存在属性“ngModel”。((更改)="log(ngModel)"ngModel)
有人可以指导我正确的方向吗?
我在 StackOverFlow 中发现了类似的问题,但该修复不起作用。我也使用那里提到的相同教程。我目前正在使用 Angular 10,本教程是 Angular 4
另外,ngModel 在这里是什么意思?我了解 [(ngModel)] 是一种双向绑定。和 [ngModel] 将是一个属性, (ngModelChange) 将是一起事件,它们形成 2way 绑定。独立的 ngModel 代表什么?
解决方案
使用您的代码,您创建了一个template-reference-variable。这意味着firstName
现在具有指令的属性ngModel
。
我不认为这是你想要的。也许这样的东西适合你:
<input type="text" name="firstName" (ngModelChange)="log($event)" class="form-control"/>
推荐阅读
- xml - 从帐户 .blob.core.windows.net 中的 blob 容器 mycontainer 读取 XML 时出错
- installation - 防止 NSIS “错误打开文件进行写入”
- r - 数据框的大小?
- html - flexbox:两个垂直图标之间没有空格
- html - 如何使用带有更改/有限文本的 XSLT 创建超链接
- java - 具有相同返回类型的方法的 Mockito 默认行为和自定义行为
- ubuntu - 为什么 Docker 在我的 Selenium 项目中看不到驱动程序可执行文件?它抛出驱动程序可执行文件不存在
- javascript - 如何在 textarea 下放置一个 div 并能够处理其上的事件?
- java - Json 没有出现
- robotium - Botium-脚本内存