Angular 4中为FormArray内新增FormControl的下拉框设置默认值
Feedback & Optimizations for Your Angular 4 FormArray Default Value Setup
Hey there! Let's break down your current implementation and go over some improvements and potential pitfalls to watch out for:
Potential Issues in the Current Code
- Missing null/undefined handling for sessionStorage data: If
sessionStorage.getItem("allItems")returnsnull(e.g., the key doesn't exist or was cleared),JSON.parse(null)will throw an error. You need to handle this edge case gracefully. - Redundant
self = thisassignment: Since you’re using an arrow function inaddMore(), thethiscontext is already bound to your component instance—you don’t need to create aselfvariable to reference it. - Manual form control instantiation: Angular’s
FormBuilderis built to simplify form creation with a more concise, readable syntax, instead of manually callingnew FormGroupandnew FormControlevery time. - Outdated type assertion style: Using
<FormArray>works for type assertion, but TypeScript recommends theas FormArraysyntax for better clarity and to avoid conflicts with JSX-like code. - Post-creation default value setup: You can set the default value directly when initializing the
FormControlinstead of callingsetValueafterward, which makes the code more straightforward and cohesive.
Optimized Implementation
Here’s a cleaned-up version incorporating these fixes:
import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; import _ from 'lodash'; // Inject FormBuilder in your component constructor first constructor(private fb: FormBuilder) {} createBarWithData(): FormGroup { // Safely retrieve and parse sessionStorage data const storedItems = sessionStorage.getItem("allItems"); const data = storedItems ? JSON.parse(storedItems) : []; // Use FormBuilder to create the FormGroup, with default value set directly in FormControl return this.fb.group({ allItem1: [_.head(data) || null], // Fallback to null if data is empty or undefined allItem2: [], allItem3: [], allItem4: [] }); } addMore(): void { // No need for self = this—arrow functions preserve the component's this context this.allItemsKnown.push(this.createBarWithData()); } get allItemsKnown(): FormArray { // Use TypeScript's recommended type assertion syntax return this.customerForm.get('ItemsKnown') as FormArray; }
Additional Recommendations
- Cache static sessionStorage data: If the
allItemsdata in sessionStorage doesn’t change during the component’s lifecycle, parse it once inngOnInit()and reuse the parsed data instead of fetching/parsing it every timecreateBarWithData()runs. This boosts performance:private allItemsData: any[] = []; ngOnInit(): void { const storedItems = sessionStorage.getItem("allItems"); this.allItemsData = storedItems ? JSON.parse(storedItems) : []; } createBarWithData(): FormGroup { return this.fb.group({ allItem1: [_.head(this.allItemsData) || null], // ... other controls }); } - Add type safety: Define an interface for your form model to avoid
anytypes and get better TypeScript checks. For example:interface BarForm { allItem1: string; // Replace with your actual data type (e.g., number, custom interface) allItem2: string; allItem3: string; allItem4: string; } createBarWithData(): FormGroup<BarForm> { // ... implementation } - Flexible value updates: If you ever need to update only a subset of form controls later, use
patchValueinstead ofsetValue—it’s more forgiving for partial updates. For your current use case though, setting the default during control initialization is the cleanest approach.
内容的提问来源于stack exchange,提问作者digish a d
相关产品推荐
相关产品推荐

