当我要定义变量时,ngModel中出现什么问题?

时间:2019-10-22 17:06:29

标签: html angular

我想使用ngModel,但是有问题。
该代码未运行,并且给我一个错误。

这是我的代码:

contact-form.component.html

<div class="container">
<form>
    <div class="form-group">
        <label for="firstName">First name</label>
        <input ngModel #firstName="firstName" (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
    </div>

    <div class="form-group">
        <label for="comment">comment</label>
        <textarea id="comment" rows="3" class="form-control"></textarea>
    </div>

    <button class="btn btn-primary">Enter</button>
</form>

</div>

contact-form.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-contact-form',
  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  log(f) {
    console.log(f);
  }

}

,并且此错误显示在控制台中:

Error: Template parse errors:
There is no directive with "exportAs" set to "firstName" ("  <div class="form-group">
        <label for="firstName">First name</label>
        <input ngModel [ERROR ->]#firstName="firstName" (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
  "): ng:///AppModule/ContactFormComponent.html@4:23

我该怎么办?

3 个答案:

答案 0 :(得分:1)

以如下形式修改您的输入标签:

<input  #firstName="ngModel" (change)="log(firstName)" 
 type="text" class="form-control"/>

注意:如果要进行双向数据绑定( [(ngModel)] =“ propName” ):

<input  #firstName="ngModel" (change)="log(firstName)" [(ngModel)]="firstName"
     type="text" class="form-control"/>

答案 1 :(得分:0)

  • 对于您的输入标签,请使用此标签。这将破坏双向数据绑定。

    <input #firstName (change)="log(firstName)" type="text">
    
    - and to display its content use it as interpolation syntax in your template. 
    
    {{firstName.value}}
    - after you done text input press enter and results will be in interpolation.
    
  • 第二种方法是..

  • 在这种情况下,您还需要在组件类中定义属性名称。

    private firstName;
    
    • 并在您的模板文件中

       <input [ngModel]="firstName" (ngModelChange)="firstName = $event" >
      
       {{ firstName }}
      
  • 确保在项目的主应用模块中导入FormsModule

     import { FormsModule } from '@angular/forms';
    
  • 如果要访问component.ts文件中的模板引用变量,则必须使用@ViewChild()指令。并且只能在ngAfterViewInit()生命周期方法中使用。

     @ViewChild ('firstName', { static: false}  ) inputRefElm : ElementRef;
    
     ngAfterViewInit(){
         console.log(this.inputRefElm.nativeElement.value);
     }
    

答案 2 :(得分:0)

您可以尝试以下方法:

<div class="form-group">
        <label for="firstName">First name</label>
        <input [(ngModel)]="firstName" #firstName (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
    </div>