Angular2 Form

本文详细介绍了Angular中表单的导入指令、视图注入、模板配置及常见属性使用,包括基本表单创建、双向绑定、控件分组等高级特性,并通过实例展示了如何在提交表单后获取数据。

1 basic usage

1 import formDirectives 

import {formDirectives} from 'angular2/forms';

2 inject directive into View

directives: [formDirectives]

3 config your form template

    template: `<form #f="form" (submit)="onSubmit(f.value)">
                <input type="text" ng-control="username" />
                <input type="text" ng-control="password"/>
                <button type="submit">submit</button>
              </form>`,

    take care : 1 #f='form' 2 ng-control

      after you submit you will get the result like {username:xx,password:xx}

4 all the code

/**
 * Created by Administrator on 2015/7/24.
 */
import {Component,View} from 'angular2/angular2';
import {formDirectives} from 'angular2/forms';

@Component({
    selector: 'form-test'
})

@View({
    template: `<form #f="form" (submit)="onSubmit(f.value)">
                <input type="text" ng-control="username" />
                <input type="text" ng-control="password"/>
                <button type="submit">submit</button>
              </form>`,
    directives: [formDirectives]
})

export class FormTest {
    constructor() {
    }

    onSubmit(formGroup) {
        console.log(formGroup);
    }
}

  

2 two-way binding

use [(ng-model)]='xxxx'

@View({
    template: `<form #f="form" (submit)="onSubmit(f.value)">
                <input type="text" ng-control="username" [(ng-model)]="login.userName"/>
                <input type="text" ng-control="password" [(ng-model)]="login.password"/>
                <button type="submit">submit</button>
              </form>`,
    directives: [formDirectives]
})

  

3 ng-control-group

@View({
    template: `<form #f="form" (submit)="onSubmit(f.value)">
                <div ng-control-group="basic">
                    <input type="text" ng-control="username" [(ng-model)]="login.basic.userName"/>
                    <input type="text" ng-control="password" [(ng-model)]="login.basic.password"/>
                </div>
                <div ng-control-group="company">
                    <input type="text" ng-control="companyname" [(ng-model)]="login.company.companyName"/>
                </div>
                <button type="submit">submit</button>
               </form>`,
    directives: [formDirectives]
})

  use ng-control-group, you will get the result like 

  

this.login = {
            basic: {
                userName: 'Jackey',
                password: '123'
            },
            company: {
                companyName: ''
            }
        }

  

 

转载于:https://www.cnblogs.com/lihaozhou/p/4665674.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值