[Angular] FormBuildAPI
2023-09-14 09:00:52 时间
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的Observable可观察对象(转)
- [Angular] @ContentChild with Directive ref
- [Angular] Test Directive
- [Angular] Working with FormArray
- [Angular Directive] Build a Directive that Tracks User Events in a Service in Angular 2
- [Angular 2] ROUTING IN ANGULAR 2 REVISITED
- [AngularJS] Using the Angular scope $destroy event and method
- 如何根据SAP Spartacus的页面快速找到实现的Angular Component
- Angular Component模板里的元素,运行时如何被生成并插入到DOM tree中
- paip.提升效率--数据绑定到table原理和流程Angular js jquery实现
- Angular CLI的安装和使用
- Angular jasmine.expect单步调试