首页 > 解决方案 > 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);
 }

}

收到以下错误:

  1. 没有找到 exportAs 'ngModel' 的指令。(name="firstName" #firstName = "ngModel")
  2. “FormContactComponent”类型上不存在属性“ngModel”。((更改)="log(ngModel)"ngModel)

有人可以指导我正确的方向吗?

我在 StackOverFlow 中发现了类似的问题,但该修复不起作用。我也使用那里提到的相同教程。我目前正在使用 Angular 10,本教程是 Angular 4

另外,ngModel 在这里是什么意思?我了解 [(ngModel)] 是一种双向绑定。和 [ngModel] 将是一个属性, (ngModelChange) 将是一起事件,它们形成 2way 绑定。独立的 ngModel 代表什么?

标签: angulartypescript

解决方案


使用您的代码,您创建了一个template-reference-variable。这意味着firstName现在具有指令的属性ngModel

我不认为这是你想要的。也许这样的东西适合你:

<input type="text" name="firstName" (ngModelChange)="log($event)" class="form-control"/>

推荐阅读