Step 1
ng new directive-demo
cd directive-demo
Step 2:
Open app.component.ts file and puth the contents as below:
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { NgFor, NgClass, NgIf } from '@angular/common';
@Component({
selector: 'app-root',
imports: [CommonModule,NgFor, NgIf, NgClass],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'directive-demo';
movies = [
'Amaran',
'Coolie',
'Vikram',
'Pushpa',
'Animal'
]
}
---------------------------------------------------------------------------------------------------------------
Open app.component.html and put the contents as follows:
li<h1>
ngFor Example
</h1>
<ul>
<li *ngFor="let movie of movies">{{movie}}</li>
</ul>
<!-- index -->
<h3> index Example</h3>
<ul>
<li *ngFor="let movie of movies; let i = index">
{{i+1}}-{{movie}}</li>
</ul>
<!-- First and Last -->
<h3> First and Last Example</h3>
<ul>
<li *ngFor="let movie of movies; let isFirst=first; let isLast=last">
<strong *ngIf="isFirst">First:</strong>
<strong *ngIf="isLast">Last:</strong>
{{movie}}
</li>
</ul>
<!-- Odd & Event -->
<h3>
ngFor ODD & even Example
</h3>
<ul>
<li *ngFor="let movie of movies; let isEven= even; let isOdd=odd;"
[ngClass]="{'even-item': isEven, 'odd-item': isOdd}"
>
{{movie}}
</li>
</ul>
---------------------------------------------------------------------------------------------------------------
Open the file app.component.css and the make the contents as shown:
.even-item {
background-color: rgb(139, 216, 139);
}
.odd-item {
background-color: rgb(235, 238, 241);
}
---------------------------------------------------------------------------------------------------------------
ng serve to see the browser similar to as shown below