html - Primeng p-selectButton 不适用于 Reactive Forms

标签 html angular primeng angular-reactive-forms

我使用的是响应式(Reactive)表单,我有一个带有 formControlName“Angular 色”的 p-selectButton。

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

这是我的代码:

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 选项,“Angular 色”:

[
  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 通过对象引用确定条目是否相等。所以数组中的值需要是同一个对象,而不仅仅是具有相同值的对象。因此,如果您有一个包含 Angular 色对象的 user,最简单的方法是在您的 roles 数组中找到相应的 role 对象,方法是 _id;

// 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.

关于html - Primeng p-selectButton 不适用于 Reactive Forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59543576/

相关文章:

html - 无需更改布局即可访问占位符文本

javascript - jquery禁用状态未正确触发

javascript - 用可重复的纹理填充图像

javascript - 如何手动取消选中/选中 primeng 复选框

javascript - Angular 重置下拉值 primeng

html - 试图让容器 div 中的所有内容响应

typescript - 如何更新 typings.json 和 typing 文件?

angular - 根据屏幕大小更改 md-grid-list 的布局或 cols 值

angular - dart2js 试图编译 css?

angular - 获取当前页面并移动到 Primeng 数据表中的特定页面