Primeng p-selectButton 不适用于响应式表单



我正在使用一个反应式表单,我有一个带有formControlName"role"的p-selectButton。

我想做的是,将活动的 p-selectButton 选项与我从用户那里收到的数据放在一起,但这不起作用。我在文档中找不到解决方案,因为只显示了如何将它与 [(ngModel(]...

这是我的代码:

TS

this.form = new FormGroup({
role: new FormControl(null, Validators.required)
});

.html

<p-selectButton [options]="roles" formControlName="role" optionLabel="name" multiple="multiple"></p-selectButton>

我所有的p-selectButton选项,"角色":

[
0:
_id: "5e00a7240742771f183a9f55"
name: "ADMIN"
role: "ADMIN_ROLE"
1:
_id: "5e00bf010930fa2b5c7d92a1"
name: "Ventas"
role: "USER_ROLE"
]

我想从我的用户激活的 p 选择按钮:

user: {
role: [
0: {
_id: "5e00a7240742771f183a9f55"
name: "ADMIN"
role: "ADMIN_ROLE"
}
]
}

这就是我在表单中引入所选数据的方式(我不知道,这是最好的方法吗? :D(

this.form.get('role').setValue(user.role);

如果我在控制台中显示form.value.role,我可以看到预期值,但在前端没有显示活动的p-selectButton!!我留下了一些东西?????

提前感谢!

发生这种情况是因为您将multiple属性设置为true。这让p-selectButton期望数组作为基础模型。因此,您需要将其初始化为数组,并将值设置为具有一个条目的数组。

public form:FormGroup = this.fb.group({
role: [[], [Validators.required]] // Array as value
});
constructor(
private fb:FormBuilder
) {}
ngOnInit() {
// You can set this everywhere else as well, and yes, this way of setting a value is okay
this.form.get('role').setValue([this.roles[1]]); // Array with 1 entry as value
}

不过,一个小缺陷是,p-selectButton通过对象引用确定条目相等。因此,数组中的值必须是相同的对象,而不仅仅是具有相同值的对象。因此,如果您有一个包含角色对象的user,最简单的方法是通过_idroles数组中找到相应的role对象;

// Your array that is bound to [options]
public roles = [{
_id: "5e00a7240742771f183a9f55",
name: "ADMIN"   
role: "ADMIN_ROLE"
}, {
_id: "5e00bf010930fa2b5c7d92a1",
name: "Ventas",
role: "USER_ROLE"
}];
// Your user, this will most likely come from somewhere else, but I suspect it looks like this
public user = {
// ... some other properties
role: {
_id: "5e00a7240742771f183a9f55",
name: "ADMIN",
role: "ADMIN_ROLE"
}
}
public form:FormGroup = this.fb.group({
role: [[], [Validators.required]]
});
constructor(
private fb:FormBuilder
) {}
ngOnInit() {
this.form.get('role').setValue([
// Find the role that the user has and use the object from roles array
this.roles.find(role => role._id === this.user.role._id)
]);
}

这是一个工作的堆栈闪电战。

最新更新