16 June 2019
Angular (4) -- Data binding and Directives
by Jerry Zhang
Day 12:
Data binding
String Interpolation
We can define properties or methods in the ts file
export class ServerComponent {
serverId = 10;
serverStatus = 'offline';
getServerStatus() {
return this.serverStatus;
}
}
Then, we can use them in the html file by String Interpolation.
<p>Server with ID {{ serverId }} is {{ serverStatus }}</p>
Or
<p>Server with ID {{ serverId }} is {{ getServerStatus() }}</p>
Property binding
We can dynamically change some properties of our DOM elements at runtime by using property binding. The code below will change the “disabled” property of a button in 2 seconds.
export class ServersComponent implements OnInit {
allowNewServer = false;
constructor() {
setTimeout(() => {
this.allowNewServer = true;
}, 2000);
}
ngOnInit() {
}
}
<button
class="btn btn-primary"
[disabled]="!allowNewServer">Add Server</button>
If we want to display a property in a <p> tag, we can bind the “innerText” property of it with our own attributes in the typescript code.
<p [innerText]="allowNewServer"></p>
The innerText property of an element is just the text content inside this element.
- Don’t mix property binding and string interpolation
Inside the double quotation mark of property binding, we must write typescript expression.
Event binding
We can create an event in our typescript code.
onCreateServer() {
this.serverCreationStatus = 'Server was created!';
}
Then, add an Angular event binding with parentheses.
<button
class="btn btn-primary"
[disabled]="!allowNewServer"
(click)="onCreateServer()">Add Server</button>
If we need to pass some data with an event, we can use $event as a parameter.
<input
type="text"
class="form-control"
(input)="onUpdateServerName($event)">
<p>{{ serverName }}</p>
onUpdateServerName(event: Event) {
// console.log(event);
this.serverName = (event.target as HTMLInputElement).value;
}
-
IMPORTANT! $event is a reserved variable name which can be used in the template when using event binding. $event will be the data emitted by that event.
-
VERY USEFUL: We can use console.log(event) to see what’s inside an event.
Tow-Way-Binding
Use ngModel directive to bind an input element with a model.
<input
type="text"
class="form-control"
[(ngModel)] ="serverName">
Directives
Directives are instructions in the DOM.
Built-in directives:
ngIf
Add a boolean attribute named serverCreated and initialize it to false. Then change it to true when the button is clicked. Then in the html we can add aline like this:
<p *ngIf="serverCreated">Server was created, server name is {{ serverName }}</p>
- Notice: the star before ngIf is necessary. This tells Angular that this is structural directive and will change the structure of our DOM.
This paragraph will be displayed only if the condition is satisfied.
We could also add an else:
<p *ngIf="serverCreated; else noServer">Server was created, server name is </p>
<ng-template #noServer>
<p>No server was created!</p>
</ng-template>
ngStyle
We can dynamically change the style using ngStyle
<p [ngStyle]="{backgroundColor: getColor()}">Server with ID {{ serverId }} is {{ getServerStatus() }}</p>
getColor() {
return this.serverStatus === 'online' ? 'green' : 'red';
}
ngClass
ngClass allows us to dynamically add or remove css classes.
First, add a style for our component.
styles: [`
.online {
color: white;
}
`]
Second, specify the condition that this class is applied.
<p
[ngStyle]="{backgroundColor: getColor()}"
[ngClass]="{online: serverStatus === 'online'}"
>Server with ID {{ serverId }} is {{ getServerStatus() }}</p>
So the online class will be used only if our status is online.
ngFor
We create a new attribute called servers, which is an array. Every time we create a new server, we push the server name into this array. Then we can loop this array and display each server with our server component.
<app-server *ngFor="let server of servers"></app-server>
Another example is using the index
keyword in the loop.
<div
*ngFor="let logItem of logs; let i = index"
[ngStyle]="{backgroundColor: i >= 4 ? 'blue' : 'transparent'}"
[ngClass]="{'white-text': i >= 4}"
>{{ logItem }}</div>
tags: Angular