Angular 4 : rendering different with input type color in a form or not

China☆狼群 提交于 2019-12-08 06:45:50

问题


I'm working on an app built with JHipster and Angular 4.3. I've a problem with the use of input type color in an angular form. I need a color picker to change a color attribute. First I just displayed values of a list (ctrlColors) and a color picker, it was OK. But the users need to customize the colors, so I made a form. Now when I load my page, I don't have all the colors displayed, but only the last of the list (screen below)

I've followed this simple example : input type color example with Angular And I built my form with Angular.io documentation and this.

I've a model ControlColor.model.ts like this :

export class ControlColor implements BaseEntity {
    constructor(
        public id?: number,
        public color?: string,
        public control?: Control,
    ) {
    }
}

In an other component I have this in MyComponent.html :

<form #ctrlColorForm="ngForm" (ngSubmit)="submitColors(ctrlColorForm.form);">
    <table>
        <tr *ngFor="let ctrl of ctrlColors">
            <td>{{ctrl.control}} :</td>
            <td>
                <input type="color"
                       [(ngModel)]="ctrl.color"
                       #nameField="ngModel"
                       name="color"
                       (ngValue)="ctrl.color"
                style="color-rendering: {{ctrl.color}}"/>
            </td>
            <td>{{ctrl.color}}</td>
        </tr>
    </table>
    <button type="submit" class="btn btn-sm">
        <span class="fa fa-pencil"></span>
        <span class="d-none d-md-inline" jhiTranslate="entity.action.edit">Edit</span>
    </button>
</form>

The strange part is that when I remove the <form> balise, the rendering is Ok (I have the right colors sent from my server and I can edit the colors), but when I put the form balise, I have this :

I have the right RGB codes (displayed on the right). Does anybody have an idea ?


回答1:


The problem is caused by the fact that all input elements have the same name (name="color"). According to Angular documentation:

When using the ngModel within <form> tags, you'll also need to supply a name attribute so that the control can be registered with the parent form under that name.

If you make the input control names different, the color will be displayed correctly in each one, as shown in this stackblitz:

<tr *ngFor="let ctrl of ctrlColors; let i=index">
    ...
    <td>
        <input type="color" [(ngModel)]="ctrl.color" name="color_{{i}}" ... />
    </td>
    ...
</tr>


来源:https://stackoverflow.com/questions/48795981/angular-4-rendering-different-with-input-type-color-in-a-form-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!