首页 > 代码库 > [Angular] FormBuildAPI

[Angular] FormBuildAPI

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