在模板 user.component.html 中我使用 Primeng 的组件
<p-multiSelect name="roles_id" [(ngModel)]="selectedRoles" [options]="user.roles"></p-multiSelect>
这段代码在user.component.ts中
export class UserComponent implements OnInit {
private selectedStores: string[];
constructor(private roleService: RoleService){
this.roleService.getRoleList().subscribe(response =>
{this.user.roles=response.body.data.map(function(value){
return {label:value.name, value: value.id};
})
})
this.selectedRoles=['1','2'];
}
ngOnInit() {
this.user={
roles: [],
};
}
}
但是在界面多选中显示 null,null ,如果我单击多选所选的两个项目。如何显示标签而不是 null,null ?
如果您将 primeng 升级到版本 ^4.0.0 就可以了
例如,您是否尝试在 console.log 中显示生成的 user.roles?
如果标签显示为空,则选项对象有问题。它必须是对象键/值的数组,以便您可以迭代它并在组件中显示。这是我正在从事的一个项目中的一个例子:
columns = [
{ value: 'id', label: 'ID' },
{ value: 'comment', label: 'Comments' },
{ value: 'updated_at', label: 'Last Update' },
{ value: 'enabled', label: 'Enabled' }
];
显然,您正在为用户对象分配一个空数组,这可能会覆盖构造函数中先前的定义。构造函数在 ngOnInit 之前运行。 您可以将 user.roles 初始化为空并在 ngOnInit() 中为其分配数据。
希望有帮助。
有趣的是,通过你的问题我找到了解决方案。我的问题是创建一个数据表,并在选择一行时显示已分配的用户角色。所以我会为你分解它。希望它能帮助你弄清楚你的。
export interface IStaff {
staffId: number;
userRoles: string[];
}
export class UserComponent implements OnInit {
staff: IStaff;
staffRoles: SelectItem[];
selectedRoles: string[] = [];
tempRoles: string[] = [];
constructor(private roleService: RoleService){}
ngOnInit() {
this.roleService.getRoleList().subscribe(response=> {
let tempRoles: IStaff[];
this.staffRoles = [];
tempRoles = response;
tempRoles.foreach(el => {
this.staffRoles.push({
label: el.name, value: el.id
});
});
});
staff.userRoles.forEach(el => {
let value: any = el;
this.tempRoles.push(value.roleName);
this.selectedRoles = this.tempRoles;
});
// then set the tempRoles back to null to prevent readding the existing roles
this.tempRoles = [];
}
}
<p-multiSelect name="roles_id" [(ngModel)]="selectedRoles" [options]="staffRoles"></p-multiSelect>