How to use Object.keys() Method In Angular
The Object.keys() method returns an Array Iterator object with the keys of an object. We will get those keys of our object and iterate over the object using ngFor.
Example: This is another example that illustrates iterating over them using ngFor in Angular.
HTML
<!-- app.component.html --> < h2 style = "color: green" >w3wiki</ h2 > < h2 >Loop through Object with *ngFor </ h2 > < li * ngFor = "let key of keys()" >{{key}}:{{states[key]}}</ li > |
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 Loop through Object with *ngFor in Angular ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will learn Loop through Object with *ngFor in Angular.
Table of Content
- Steps for Installing & Configuring the Angular Application
- Project Structure
- Using Pipe
- Using Object.keys() Method