【问题标题】:Primeng p-selectButton doesn't work with Reactive FormsPrimeng p-selectButton 不适用于反应式表单
【发布时间】:2020-04-19 22:50:45
【问题描述】:

我使用的是反应式表单,我有一个 p-selectButton 和一个 formControlName“角色”。

我想要做的是,将活动的 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 选项,“角色”:

[
  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!我留下了什么东西??????

提前致谢!

【问题讨论】:

    标签: html angular primeng angular-reactive-forms


    【解决方案1】:

    这是因为您将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 在您的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.

    【讨论】:

      猜你喜欢
      • 2020-03-08
      • 2021-02-24
      • 2019-07-11
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2021-02-09
      • 2017-12-18
      相关资源
      最近更新 更多