简体   繁体   English

Angular2 ngModel不起作用

[英]Angular2 ngModel not working

I am trying to bind ngModel from text input but it's is not working. 我正在尝试从文本输入中绑定ngModel ,但无法正常工作。 Here is my code: 这是我的代码:

Template: 模板:

<form (ngSubmit)="onSubmit()">
    <div class="form-group">
        <input type="text" class="form-control" [(ngModel)]="message">
    </div>
    <input type="submit">
</form>

Component: 零件:

export class Component implements OnInit {
  message:string

  onSubmit() {
    console.log(this.message);
  }
}

Always getting undefined value. 总是获得不确定的值。 How to bind value from the text input to variable? 如何将文本输入中的值绑定到变量?

you have to give input a name property when using template-driven form. 使用模板驱动的表单时,必须给input一个name属性。

<input type="text" name="message" [(ngModel)]="message">

refer this simple plunker demo . 参考这个简单的插件演示

You are missing ngForm 您缺少ngForm

<form #f="ngForm" (ngSubmit)="onSubmit(f)">
      <div class="form-group">
        <input type="text" class="form-control" name="message" [(ngModel)]="message">
      </div>
      <input type="button">
    </form>

export class Component implements OnInit {
  message:string

   ngOnInit() {
this.message = "test";
}

  onSubmit(form: ngForm) {
    console.log(form.value);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM