Primeng p-selectButton 不适用于 Reactive Forms

Primeng p-selectButton doesn't work with Reactive Forms

我正在使用反应式表单,我有一个带有 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-selectButtons 选项,"roles":

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

我想从我的用户激活的 p-selectedButton:

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,最简单的方法是通过 _id;[=21= 在您的 roles 数组中找到相应的 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)
  ]);
}

这里是工作 Stackblitz.