简体   繁体   English

Angular 自动分配下拉

[英]Angular auto assign drop down

I have a drop down angular select tag here.我在这里有一个下拉 angular select 标签。 The drop down wont be selected when value being assign.分配值时不会选择下拉列表。

<select [(ngModel)]="controlType" #ctrl="ngModel" class="form-control" [ngModelOptions]="{standalone: true}">
    <option [value]="undefined" selected>SILA PILIH</option>
    <option *ngFor="let alertControl of alertControlList" [ngValue]="alertControl">{{ alertControl?.desc }}
    </option>
</select>

controlType value from DB来自 DB 的controlType

{
    "errorCode": null,
    "errorMessage": null,
    "id": "b9e86e1a-cabc-11e8-9257-31ce15c52e16",
    "createdBy": "a6ef4d81-744e-49e7-9e1d-ab74a14935d6",
    "lastModifiedBy": "a6ef4d81-744e-49e7-9e1d-ab74a14935d6",
    "createdDate": 1538977256000,
    "lastModifiedDate": 1538977256000,
    "deleted": null,
    "active": true,
    "version": 0,
    "code": "1",
    "desc": "why"
}

alertControlList value警报控制列表值

[{
    "code": "2",
    "version": "0",
    "desc": "why",
    "id": "b9e8bc3b-cabc-11e8-9257-31ce15c52e16",
    "HEX(id)": "B9E8BC3BCABC11E8925731CE15C52E16"
}, {
    "code": "1",
    "version": "0",
    "desc": "why",
    "id": "b9e86e1a-cabc-11e8-9257-31ce15c52e16",
    "HEX(id)": "B9E86E1ACABC11E8925731CE15C52E16"
}]

It's only work when i do a object mapping here.仅当我在此处进行 object 映射时才有效。 Any other simpler solution?还有其他更简单的解决方案吗?

for (let int i = 0; i < alertControlList.length; i++) {
    if (alertControlList[i].code === dropdown.code) {
        console.log('do MATCH' + i + ' code' + dropdown.code);
        controlType = alertControlList[i];
    }
}

use [selected]="alertControl.code === dropdown.code" instead.使用[selected]="alertControl.code === dropdown.code"代替。

This doesn't work directly since you are setting your option value to an object and the ngModel does not match that value so it will not show as selected.这不能直接工作,因为您将option值设置为 object 并且ngModel与该值不匹配,因此它不会显示为选中状态。 Instead.反而。 You also seem to be using both ngModel with two-way binding and ngModel with ngForm .您似乎也在使用带有双向绑定的ngModel和带有ngModelngForm Use either one.使用任何一个。 If you are using ngForm to get the form values, you can set the value on select using value and change the option value to a unique property within alertControl like code .如果您使用ngForm获取表单值,您可以使用valueselect上设置值,并将option值更改为alertControl中的唯一属性,如code

<select #ctrl="ngModel" [value]="controlType.code" class="form-control">
    <option *ngFor="let alertControl of alertControlList" [value]="alertControl.code">{{ alertControl?.desc }}</option>
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM