首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。