还是
angularjs2入门1-文件结构分析
的源码,将app名称改成basic-step4-form
每一个 input 元素都有一个 name 属性, Angular 的表单模块需要使用它为表单注册控制器。
1.创建模型类 site.ts
export class Site {
constructor(
public id: number,
public name: string,
public url: string,
public alexa?: number
) { }
}
2.创建表单组件 site-form.component.ts,diagnostic 属性用于返回这个模型的JSON形式
import { Component } from '@angular/core';
import { Site } from './site';
@Component({
moduleId: module.id,
selector: 'site-form',
templateUrl: 'site-form.component.html'
})
export class SiteFormComponent {
urls = ['www.runoob.com', 'www.google.com',
'www.taobao.com', 'www.facebook.com'];
model = new Site(1, '菜鸟教程', this.urls[0], 10000);
submitted = false;
onSubmit() { this.submitted = true; }
// TODO: 完成后移除
get diagnostic() { return JSON.stringify(this.model); }
}
3.
因为模板驱动的表单有它们自己的模块,所以我们得把 FormsModule 添加到本应用的 imports 数组中,这样我们才能使用表单
4.使用 ngModel 进行双向数据绑定
<div class="form-group">
<label for="name">网站名</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name">
</div>
每一个 input 元素都有一个 id 属性,它被 label 元素的 for 属性用来把标签匹配到对应的 input 。
每一个 input 元素都有一个 name 属性, Angular 的表单模块需要使用它为表单注册控制器。
5.通过样式,控制当不符合的时候显示样式
.ng-valid[required], .ng-valid.required {
border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
6.通过 ngSubmit 来提交表单
<form *ngIf="active" (ngSubmit)="onSubmit()" #siteForm="ngForm">