Angular2 interpolation bracket notation (instead of dot) for variables

I'm wondering if there's a Angular2 equivalent to the bracket notation in Javascript that lets you use variables to select an object property. Or a way of doing the same thing.

Consider this code:

 let selector = "foo";
 let someObject = {foo: "some content", guu: "some other content"};
 console.log(someObject[selector]); //bracket notation, logs "some content"

I've tried the following in Angular2:

  {{someObject[selector]}}
  {{someObject['selector']}}

Neither worked. Is there another way of doing it without Javascript?

2 answers

  • answered 2018-02-13 03:10 vincecampanale

    This appears to work just fine in Angular: https://stackblitz.com/edit/angular-mrky5n.

    Some reasons that it may not be working in your current application:

    1) If selector is a variable with a string selector in it, perhaps that selector variable is not available to the scope of the template (e.g. it's private on the component class, defined within a method, or lifecycle hook, etc.

    2) If selector is the property you actually want to access, perhaps there is a typo in the name of selector -- maybe the real property is selectro or selecter. This is a reason to not use this approach, since you lose Typescript's type checking. someObject.selectorr throws an error while someObject['selectorr'] goes through fine.

    3) That property has not received a value yet -- maybe the safe navigation operator would help.

  • answered 2018-02-13 03:14 estus

    Angular template syntax supports many JS features, including bracket notation.

    {{someObject[selector]}} expression assumes that both someObject and selector are component properties. This won't work if they are local variables that are defined with let.