### 表单——既重要,又复杂 #### 实例展示 > 以下实例来着angular官网
以下例子通过数据绑定与内置模板的集成,编写而来。 ```html

Hero Form

Name is required
Power is required

You submitted the following:

Name
{{ model.name }}
Alter Ego
{{ model.alterEgo }}
Power
{{ model.power }}

``` ```css /*hero-from.component.css*/ .ng-valid[required], .ng-valid.required { border-left: 5px solid #42A948; /* green */ } .ng-invalid:not(form) { border-left: 5px solid #a94442; /* red */ } ``` ```typescript // app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { HeroFromComponent } from './hero-from/hero-from.component'; @NgModule({ declarations: [ AppComponent, HeroFromComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } ``` ```typescript // hero-from.component.ts import {Component, OnInit} from '@angular/core'; import {Hero} from './Hero' @Component({ selector: 'hero-from', templateUrl: './hero-from.component.html', styleUrls: ['./hero-from.component.css'] }) export class HeroFromComponent implements OnInit { powers = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer']; model = new Hero(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet'); submitted = false; onSubmit() { this.submitted = true; } // TODO: Remove this when we're done get diagnostic() { return JSON.stringify(this.model); } ngOnInit() { } } ``` ```typescript // Hero.ts 定义数据类型 export class Hero { constructor(public id: number, public name: string, public power: string, public alterEgo?: string) { } } ``` #### 实例解析 > 该例,使用ngModel ,绑定数据,并通过 `valid` `pristine` 判断input是否有输入。最后用`submitted`控制表单模拟提交事件 html代码解析:
绑定ng内置froms模板:方法 => `#heroForm="ngForm"`
为表单元素绑定ngModule: ```html ``` 展示ngModel : 方法 => `{{ model.name }}`
判断表单内容是否输入 ```html
Name is required
``` 控制组件是否显示: 方法 => `[hidden]="!submitted"`
`submitted`为变量,受事件驱动