server.component.html
<p> server {{serverId}} is {{status}} </p>
server.component.ts
import {Component, OnInit} from '@angular/core'; import {el} from '@angular/platform-browser/testing/src/browser_util'; @Component({ selector: 'app-server', templateUrl: './server.component.html', styleUrls: ['./server.component.css'] }) export class ServerComponent implements OnInit { serverId = 0; status = 'offline'; constructor() { // choose a number between 0 and 100 this.serverId = Math.floor((Math.random() * 100) + 1); const random2 = Math.random(); if (random2 > 0.5) { this.status = 'online'; } else { this.status = 'offline'; } } ngOnInit() { } }
app.component.html
<input type="button" value="Add Server" (click)="onButtonClick()"/> <app-server *ngFor="let s of servers"></app-server>
app.component.ts
import {Component} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { servers = []; onButtonClick() { // just push a date to servers this.servers.push(new Date()); } }
Getting the Index when using ngFor
<app-server *ngFor="let s of servers;let i=index" [ngClass]="{'even':i%2==0}"></app-server>
References
https://github.com/mhdr/AngularSamples/tree/master/011/my-app