Angular 2 学习笔记--ControlGroup(控制组)

ControlGroup说明:本人对该指令的理解是在html模版上绑定控制器组,然后在组件类里面操作这些对应的模块,具体查看下面代码,一看就懂。

//our root app component
import {
  Component,
  View,
  Control,
  ControlGroup,
  ControlArray,
  Validators,
  CORE_DIRECTIVES,
  FORM_DIRECTIVES
} from 'angular2/angular2'

@Component({
  selector: 'my-app',
})
@View({
  template: `
    <div>
      <h2>Angular2 Control & ControlGroup Example</h2>
      <form [ng-form-model]="formGroup">
        <div ng-control-group="name">
          <h3>Enter your name:</h3>
          <p>First: <input ng-control="first"><span *ng-if="!ctrlFirst.valid"> [required]</span></p>
          <p>Middle: <input ng-control="middle"></p>
          <p>Last: <input ng-control="last"><span *ng-if="!ctrlLast.valid"> [required]</p>
        </div>
        <h3>What's your favorite food?</h3>
        <p><input ng-control="food"><span *ng-if="!ctrlFood.valid"> [required]</span></p>
        <h3>Name a few cities:</h3>
        <ul ng-control-group="cities">
          <li *ng-for="#ctrl of ctrlCities; #i = index"><input ng-control="{{i}}"></li>
        </ul>
        <button type="button" (click)="addCity()">Add a city</button>
      </form>
      <h3>Value:</h3>
      <pre>{{cgValue}}</pre>
      <h3>Validity:</h3>
      <pre>{{formGroup.valid}}</pre>
    </div>
  `,
  directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class App {
  ctrlFirst: Control = new Control('', Validators.required);
  ctrlMiddle: Control =  new Control('');
  ctrlLast: Control =  new Control('', Validators.required);
  ctrlFood: Control = new Control('pizza', Validators.required);
  ctrlCities: Control[] = [
    new Control(''),
    new Control(''),
    new Control('')
  ];
  citiesArray: ControlArray = new ControlArray(this.ctrlCities);
  
  formGroup: ControlGroup = new ControlGroup({
    name: new ControlGroup({
      first: this.ctrlFirst,
      middle: this.ctrlMiddle,
      last: this.ctrlLast
    }),
    food: this.ctrlFood,
    cities: this.citiesArray
  });
  
  get cgValue(): string {
    return JSON.stringify(this.formGroup.value, null, 2);
  }
  
  addCity(): void {
    this.citiesArray.push(new Control(''));
  }
}

  

转载于:https://www.cnblogs.com/my-gong/p/5655785.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值