2

I have an array of object:

keyDisabledArray=[
  {'a':false},
  {'b':true}
]

and some buttons

<button class="key" (click)="keyPressed('a')" id="a">A</button>
<button class="key" (click)="keyPressed('b')" id="b">B</button>

that must be disabled according to the content of keyDisabledArray. In this case, button 'b' must be disabled and 'a' enabled. I'm trying to use [disabled] but I'm not sure how to access the correct value in the array of objects.

EDIT: I found some ways to access the value, but all were asynchronous or demanding a full loop on the array to find the correct element, and in both cases, I see problems: how angular deal with asynchronous code in front end (?) and if it is possible to avoid a full loop on the array for every button.

Sasha Grievus
  • 2,566
  • 5
  • 31
  • 58

1 Answers1

4

You can write a pipe to extra the correct value.

Edit: see how to here to create a pipe which accepts multiple arguments How do I call an Angular 2 pipe with multiple arguments?

Edit #2: here is a sample piece of code (not tested)

import {Pipe, PipeTransform} from '@angular/core';


@Pipe({
  name: 'isDisabled'
})
export class IsDisabledPipe implements PipeTransform
{

  transform(array: any, key: string): any
  {

    let val = array.find(v => v.hasOwnProperty(key));
    return val? val[key] : false;

  }

}

you can then use it like

 <button class="key" [disabled]="keyDisabledArray | isDisabled:'a'" (click)="keyPressed('a')" id="a">A</button>

Otherwise, why don't you convert your array to a json object?

keyDisabledArray=
{
  'a':false,
  'b':true
};

then, accessing the value will be easier

<button class="key" [disabled]="keyDisabledArray['a']" (click)="keyPressed('a')" id="a">A</button>
David
  • 33,444
  • 11
  • 80
  • 118