NgFor
NgFor
is a structural directive, meaning that it changes the structure of the DOM.
1) app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent } from './app.component';
import { StudentListComponent } from "./student-list.component";
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent,StudentListComponent],
bootstrap: [AppComponent],
})
export class AppModule { }
2) app.component.ts
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'project-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
message:string;
constructor() {
this.message = "Student List";
}
}
3) app.component.html
<p>{{message}}</p>
<student-list></student-list>
4) student-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Student } from "./student";
@Component({
selector: 'student-list',
templateUrl: 'student-list.component.html'
})
export class StudentListComponent{
students:Student[];
constructor() {
this.students = [new Student(1,"student1"),new Student(2,"student2")];
}
}
5) student-list.component.html
<table>
<tr><td>ID</td><td>Name</td></tr>
<tr *ngFor="let student of students">
<td>{{student.id}}</td>
<td>{{student.name}}</td>
</tr>
</table>
6) student.ts
export class Student{
id:number;
name:string;
constructor(a,b){
this.id=a;
this.name=b;
}
}