How to use Object.keys() In Angular
The Object.keys() method returns an Array Iterator object with the keys of an object. We will get the keys of our object and iterate over the object using ngFor Directive.
Example: This example illustrates the iteration over the object in Angular using Object.keys() Method.
HTML
<!-- app.component.html --> < h2 style = "color: green" > w3wiki </ h2 > < h2 > How to Iterate over object in Angular ? </ h2 > < ul > < li * ngFor = "let key of keys()" > {{key}}:{{states[key]}} </ li > </ ul > |
Javascript
// app.component.ts import { Component, OnInit } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; @Component({ selector: 'app-root' , templateUrl: "./app.component.html" , styleUrls: [ './app.component.css' ] }) export class AppComponent { states: Dictionary; constructor() { this .states = { 'Uttar Pradesh' : 'Lucknow' , 'Tripura' : 'Agartala' , 'West Bengal' : 'Kolkata' , 'Rajasthan' : 'Jaiput' }; } keys(): Array<string> { return Object.keys( this .states); } } interface Dictionary { [index: string]: string } |
Javascript
// app.module.ts import { NgModule } from '@angular/core' ; import { BrowserModule } from '@angular/platform-browser' ; import { HttpClientModule } from '@angular/common/http' ; import { AppComponent } from './app.component' ; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
Output:
How to iterate over Object in Angular ?
Objects consist of a set of key-value pairs, which are known as Properties. All Properties are named in JavaScript objects and the key part represents the Property name, while the value part represents the property Value. Each element(key-value pair) of the object can be utilized to perform a specific action, as it permits access and manipulation of the properties and values stored in that object. In this article, we will see how to Iterate over object in Angular.
Table of Content
- Using Pipe
- Using Object.keys()
We will explore the above-mentioned approaches with the help of suitable examples.
Contact Us