Angular 4表单中input type color渲染异常问题咨询
Hey there! Let’s figure out this color picker issue you’re hitting with your Angular 4.3 + JHipster app. From what you described, the problem sounds like a classic case of shared form controls or incorrect binding in your loop—here’s how to fix it:
Common Root Cause
When you built the custom form, you probably ended up binding all your color pickers to the same form control or variable, which is why only the last value from your ctrlColors list sticks on page load. Each color picker needs its own independent binding to display and update its corresponding color.
Fix 1: Use FormArray for Reactive Forms (Recommended for Angular)
If you’re using reactive forms (which JHipster often leans into), you’ll want to create a FormArray to hold individual FormControls for each color in your list.
Step 1: Build the Form in Your Component
import { FormGroup, FormArray, FormControl } from '@angular/forms'; // Inside your component class myColorForm: FormGroup; ngOnInit() { // Create a FormControl for each color in ctrlColors const colorControls = this.ctrlColors.map(color => new FormControl(color.hexValue) // Replace with your color property name ); // Initialize the form with a FormArray this.myColorForm = new FormGroup({ colors: new FormArray(colorControls) }); }
Step 2: Bind to the FormArray in Your Template
<form [formGroup]="myColorForm"> <div formArrayName="colors"> <!-- Loop through both your ctrlColors list and the FormArray controls --> <div *ngFor="let color of ctrlColors; let i = index"> <span>{{ color.name }}:</span> <input type="color" [formControlName]="i" class="color-picker" > </div> </div> </form>
Fix 2: Use ngModel with Unique Identifiers (Template-Driven Forms)
If you’re using template-driven forms, make sure each color picker binds to a unique property in your ctrlColors array and has a unique name attribute (Angular requires this for form tracking).
<div *ngFor="let color of ctrlColors; let i = index"> <span>{{ color.name }}:</span> <input type="color" [(ngModel)]="color.hexValue" [name]="'color-picker-' + i" class="color-picker" > </div>
Key Things to Double-Check
- Avoid reusing the same FormControl: If you were accidentally assigning the same control to all pickers in a loop, that’s why only the last value shows up—each picker needs its own instance.
- Unique names for template-driven forms: Skipping unique
nameattributes can cause Angular to mix up form controls, leading to unexpected behavior. - Verify your ctrlColors structure: Make sure each item in the array has a distinct property (like
hexValue) that you’re binding to—no overlapping references here.
This should get all your color pickers displaying the correct initial values from ctrlColors while letting users customize each one independently.
内容的提问来源于stack exchange,提问作者Neamesis

