码迷,mamicode.com
首页 > Windows程序 > 详细

[Angular] FormBuildAPI

时间:2017-03-22 00:23:16      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:blog   ons   for   ranch   api   first   product   logs   pre   

Using FormBuilder API can simply our code, for example we want to refactor following code by using FormBuilder:

  form = new FormGroup({
    store: new FormGroup({
      branch: new FormControl(‘‘),
      code: new FormControl(‘‘)
    }),
    selector: this.createStock({}),
    stock: new FormArray([
      this.createStock({ product_id: 1, quantity: 10 }),
      this.createStock({ product_id: 3, quantity: 50 }),
    ])
  });

 

First thing we need to do is actually inject FormBuilder:

  constructor(
    private fb: FormBuilder
  ) {}

Then:

  form = this.fb.group({
    store: this.fb.group({
      branch: ‘‘,
      code: ‘‘
    }),
    selector: this.createStock({}),
    stock: this.fb.array([
      this.createStock({ product_id: 1, quantity: 10 }),
      this.createStock({ product_id: 3, quantity: 50 }),
    ])
  });

  createStock(stock) {
    return this.fb.group({
      product_id: parseInt(stock.product_id, 10) || ‘‘,
      quantity: stock.quantity || 10
    });
  }

 

So as you can see, you replace all new FormGroup() and new FormArray() by just fb.group & fb.array.

And meanwhile, we don‘t need FormControl any more, because FormBuild understand that it should be a FormControl.

 

[Angular] FormBuildAPI

标签:blog   ons   for   ranch   api   first   product   logs   pre   

原文地址:http://www.cnblogs.com/Answer1215/p/6597575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!