Angular: Directives
app/servers/servers.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-servers',
templateUrl: './servers.component.html'
})
export class ServersComponent implements OnInit {
serverCreated = false;
servers = ['Testserver, 'Testserver 2'];
constructor() {
}
ngOnInit() {
}
onCreateServer() {
this.serverCreated = true;
this.servers.push(this.serverName);
}
}
ngIf and ngFor
app/servers/servers.component.html
<p *ngIf="serverCreated">Server was created</p>
<button (click)="onCreateServer()">Add Server</button>
<app-server *ngFor="let server of servers, let i = index"></app-server>
ngIf with else condition
app/servers/servers.component.html
<p *ngIf="serverCreated; else noServer">Server was created</p>
<ng-template #noServer>
<p>No server was created</p>
</ng-template>
<button (click)="onCreateServer()">Add Server</button>
ngStyle
app/server/server.component.html
<p [ngStyle]="{backgroundColor: getColor()}"> {{serverId}} is {{getServerStatus()}} </p>
app/servers/server.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-server',
templateUrl: './server.component.html',
styles: [`
.online {
color:white;
}
`]
})
export class ServerComponent {
serverId: number = 10;
serverStatus: string = 'offline';
constructor() {
this.serverStatus = Math.random() > 0.5 ? 'online' : 'offline';
}
getServerStatus() {
return this.serverStatus;
}
getColor() {
return this.serverStatus === 'online' ? 'green' : 'red';
}
}
ngClass
app/server/server.component.html
<p
[ngStyle]="{backgroundColor: getColor()}"
[ngClass]="{'online': serverStatus==='online'}"
>
{{serverId}} is {{getServerStatus()}}
</p>