如果在数组中找到特定对象,如何返回true?

时间:2019-10-16 09:27:45

标签: arrays angular typescript

我有一个简单的表单,其中包含用Angular制作的复选框,如果用户具有此角色,我想使复选框自动检查。

这是我尝试过的:

<form [formGroup]="rolesForm">
  <label 
    formArrayName="roles" 
    *ngFor="let role of rolesForm.controls['roles'].controls; let i = index"
  >
    <input 
      type="checkbox" 
      [checked]="checkIfTrue(role[i])"
      [formControlName]="i" 
    /> {{role[i].name}}
  </label>
</form>

组件本身:

roles: Role[] = [
  {
    uid: '456DNC',
    name: 'Admin'
  },
  {
    uid: '546DKZ',
    name: 'Member'
  },
  {
    uid: '741JXY',
    name: 'Guest'
  }
]

user: User = {
  uid: '123ABC',
  name: 'Steve',
  roles: [
    {
      uid: '456DNC',
      name: 'Admin'
    }
  ]
}

rolesForm: FormGroup;

// So I can get every roles and the user can check multiple checkboxes to get as many roles as it wants
ngOnChanges() {
  const formControls = this.roles.map(role => new FormControl(false));

  this.rolesForm = this.formBuilder.group({
    roles: new FormArray(formControls)
  });
}

checkIfTrue(role: Role) {
  // I assume that it should return true if it finds the role in the user.roles array but it doesn't. It doesn't check the box and I get an eror.
  return this.user.roles.find(role);
}

我得到这样的信息:[object Object] is not a function at Array.find

我尝试了以下功能.indexOf().includes()

3 个答案:

答案 0 :(得分:2)

由于您使用的是响应式表单,因此在构建表单时应设置值,而不要使用[checked]属性。

https://stackblitz.com/edit/angular-hsvug5?file=src/app/app.component.ts

ngOnChanges() {
  const formControls = this.roles.map(role => new FormControl(this.checkIfTrue(role)));

  this.rolesForm = this.formBuilder.group({
    roles: new FormArray(formControls)
  });
}

checkIfTrue(role) {
  return this.user.roles.find(r => r.uid === role.uid);
}
<form [formGroup]="rolesForm">
  <label 
    formArrayName="roles" 
    *ngFor="let role of rolesForm.controls['roles'].controls; let i = index"
  >
    <input 
      type="checkbox" 
      [formControlName]="i" 
    /> {{roles[i].name}}
  </label>
</form>

答案 1 :(得分:0)

indexOf()如果找不到元素,则返回-1。 因此,您可以实现以下内容:

return this.user.roles.indexOf(role) != -1

通过这种方式,如果indexOf找到了元素true,那么您将拥有false

在您的checkIfTrue(role:Role)方法中

答案 2 :(得分:0)

一切都很好,只能这样更改:

 checkIfTrue(role: Role) {

   this.user.roles.find(e=>{
    if(e.name === role) {
       return true;
     }
     });
   }