Angular之ngModel使用

在 Angular 4.x 中对于使用 Template-Driven 表单场景,如果需要实现表单数据绑定。我们就需要引入 ngModel 指令。该指令用于基于 domain 模型,创建 FormControl 实例,并将创建的实例绑定到表单控件元素上。

//ngModel
//app.component.ts
@Component({
  selector: 'exe-app',
  template: `
   <form novalidate #f="ngForm">
      Name: <input type="text" name="username" ngModel>
      Password: <input type="text" name="password" ngModel>
   </form>
   {{ f.value | json }}
  `,
})
export class AppComponent implements OnInit { }

在 <form> 表单中使用 ngModel 时,我们需要设置一个 name 属性,以便该控件可以使用该名称在表单中进行注册。
显示效果图:


image.png

单向绑定 - [ngModel]

//app.component.ts
@Component({
  selector: 'exe-app',
  template: `
   <form novalidate #f="ngForm">
      Name: <input type="text" name="username" [ngModel]="user.username">
   </form>
   {{ user | json }}
  `,
})
export class AppComponent implements OnInit {
  user: { username: string };

  ngOnInit() {
    this.user = { username: 'Semlinker' };
  }
}

双向绑定 - [(ngModel)]
表单中应用

//app.component.ts
@Component({
  selector: 'exe-app',
  template: `
   <form novalidate #f="ngForm">
      Name: <input type="text" name="username" [(ngModel)]="user.username">
   </form>
   {{ user | json }}
  `,
})
export class AppComponent implements OnInit {
  user: { username: string };

  ngOnInit() {
    this.user = { username: 'Semlinker' };
  }
}

单独应用

import { Component } from '@angular/core';
@Component({
  selector: 'exe-app',
  template: `
    <input name="username" [(ngModel)]="username">
    {{username}}
  `,
})
export class AppComponent {
  username: string;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 细说 Angular 2+ 的表单(二):响应式表单 摘要 在企业应用开发时,表单是一个躲不过去的事情,和面向消费...
    接灰的电子产品阅读 5,951评论 8 28
  • 版本:Angular 5.0.0-alpha 表单是商业应用的支柱,我们用它来执行登录、求助、下单、预订机票、安排...
    soojade阅读 1,343评论 0 1
  • 在 Angular 4.x 中对于使用 Template-Driven 表单场景,如果需要实现表单数据绑定。我们就...
    semlinker阅读 3,903评论 0 5
  • angular提供了模板驱动和模型驱动两种方式来构建表单。模板驱动模式使用模板表单内置指令、内置校验的方式来构建表...
    oWSQo阅读 946评论 0 0
  • 在学习各种高级编程语言的过程中,我们总会遇到一些语言类型的名词,理解这些名词对我们理解高级语言的运行机制有很大帮助...
    呼呼君是什么君阅读 648评论 0 0

友情链接更多精彩内容