[英]Set default value for dropdown list FormGroup
我有2个来自API的响应数据,例如:列出所有角色:
{
"content": [{
"id": 1,
"roleName": "admin",
},
{
"id": 2,
"roleName": "user",
},
{
"id": 3,
"roleName": "other",
}
],
"last": true,
"totalElements": 3,
"totalPages": 1,
"size": 20,
"number": 0,
"first": true,
"sort": null,
"numberOfElements": 3
}
和用户信息:
{
"id": 1,
"userName": "admin"
userRole[
"id": 1,
"roleName": "admin",
]
}
在HTML中,我想显示列表角色:
<div class="form-group">
<label>Roles</label>
<select formControlName="roles" class="form-control" id="roles">
<option>{{user.userRole.roleName}}</option>
<option *ngFor="let ls of roles">{{ls.roleName}}</option>
</select>
</div>
但是,用户界面显示:[admin],[admin],[user],[other]
我尝试通过使用* ngIf删除重复角色:
<div class="form-group">
<label>Roles</label>
<select formControlName="roles" class="form-control" id="roles">
<option>{{user.userRole.roleName}}</option>
<option *ngFor="let ls of roles">
<div *ngIf="user.userRole.roleName!=ls.roleName">{{ls.roleName}}</div>
</option>
</select>
</div>
但用户界面显示:[admin],[空白],[用户],[其他]
请建议我正确显示列表角色。
<div class="form-group">
<label>Roles</label>
<select formControlName="roles" class="form-control" id="roles">
<option *ngFor="let ls of roles" [selected]="ls.id === user.userRole.id">
{{ls.roleName}}
</option>
</select>
</div>
我找到了用户[attr.selected]的解决方案:
<select formControlName="roles" class="form-control" id="roles" >
<option *ngFor="let rl of roles;"
[attr.value]='rl.id'
[attr.selected]="rl.id == desc ? true : null">
{{rl.roleName}}
</option>
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.