表单模型

在使用 ngModel 进行输入框的数据双向绑定之前, 需要先引入对应模块, 否则, 会报以下错误:

Can't bind to 'ngModel' since it isn't a known property of 'input'.

第一步: 在文件 app.component.ts 中引入ngModel

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
@NgModule({
  imports: [
    FormsModule
  ]
})
export class AppModule { }

第二步: 在对应的的模板中使用

import { Component } from '@angular/core';
@Component({
  selector: 'app-test',
  template: `
    <div>
      <label>name:
        <input [(ngModel)]="name" placeholder="name">
      </label>
      <div>{{name}}</div>
    </div>
  `
})
export class TestComponent {
  name: String = '';
}

注意写法:

<input [(ngModel)]="name" placeholder="name">

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress