Search code examples
angularecmascript-6angular-ng-if

Angular *ngIf check if key exists in map


I have a map that looks like:

let mapToSearch =
{
  'aaa': '123',
  'bbb': '456'
}

and I have a variable:

let keyToFind = 'aaa';

In my HTML template, in an Angular *ngIf block, I want to check if keyToFind matches any key within this map.

Something like JS array.indexOf():

<ng-container *ngIf="mapToSearch.indexOf(keyToFind)">
  Hello world
</ng-container>

Is such a thing possible with maps within a template?


Update (including Solution)

Thanks for all your answers. All your answers are valid for working with a object literal (this was my mistake - I should have declared the map differently in the question).

However, for a ES6 map, I discovered I can use map.has(key) in the template.

Declare map with map.set():

let mapToSearch = new Map();
mapToSearch.set('aaa', '123'};
mapToSearch.set('bbb', '456'};

Template:

<ng-container *ngIf="mapToSearch.has(keyToFind)">
  Hello World
</ng-container>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has


Solution

  • Be careful of the performance hit you take when supplying an expression and not a primitive to the *ngIf directive. If you supply an expression or function then Angular's digest cycle will have to evaluate the expression every time. To test, add a console.log() statement to a function inside ngIf - *ngIf="showMyElement()" - and watch how many times it gets called when you navigate around your application.

    Melindu's answer is pretty good (for your case I would do this) - *ngIf="mapToSearch[keyToFind]"

    A good habit to get into is to setup a boolean in your component and update that boolean anytime your collection/object changes. Generally when you have more complex scenarios there aren't too many operations on the page that requires that boolean to be updated. So it's better to track those changes yourself in the component, than it is to let angular reevaluate an expression or function every digest.

    app.html

    <div *ngIf="keyIsFound"></div>
    

    component.ts

    keyIsFound: boolean;
    mapToSearch = {};
    
    private checkKey(key: string) {
        this.keyIsFound = this.mapToSearch[keyToFind]
    }
    // Collection changes
    addToMap(newKey: string, newValue: any) {
       this.mapToSearch[newKey] = newValue;
       checkKey(newKey);
    }