Angular Data Binding and Lifecycle Hooks

Classified in Design and Engineering

Written at on English with a size of 6.1 KB.

Binding

One Way Binding

{{pageTitle}}

Two Way Binding
Property Binding
Attribute BindingOk
Class Binding
Selected
ngClass

{{customer.name}}
Style Binding
ngStyle

{{customer.name}}
Component Binding
Directive Binding
Customer
Event BindingSave
$event

Lifecycle Hooks

OnInitexport class Customer implements OnInit {
ngOnInit() {}
}
OnChangesexport class Customer implements OnChanges {
ngOnChanges() {}
}
AfterViewInitexport class Customer implements AfterViewInit {
ngAfterViewInit() {}
}
OnDestroyexport class Customer implements OnDestroy {
ngOnDestroy() {}
}

Pipes

Upper Case

{{customer.name | uppercase}}

Lower Case

{{customer.name | lowercase}}

Date

{{orderDate | date:'medium'}}

Date Format

{{orderDate | date:'yMMMd'}}

Currency

{{price | currency}}

Percent

{{taxes | percent:'1.1-1'}}

Number

{{value | number:'1.1-2'}}

JSON Debugging
{{Customer | json}}

Component with Inline Template

import { Component } from '@angular/core';

@Component({
moduleId: module.id,
selector: 'customer',
template: `

{{customer.name}}


`
})
export class CustomerComponent {
customer = { id: 100, name: 'John Smith' };
}

Structural Directives

*ngIf

Selected {{currentCustomer.Name}}
*ngFor


  • {{ customer.name }}

*ngSwitch

Service

//Example: customer.service.ts
import { HttpModule } from '@angular/http'
@Injectable()
export class CustomerService {
constructor(private http: Http) { }
getCustomers() {
return this.http.get('api/customers')
.map((response: Response) => response.json().data)
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Service error');
}
}

Injecting a Service

//Example: customer-list.component.ts
export class CustomerListComponent {
customers: Customer[];
constructor(private customerService: CustomerService) { }
}

Component Linked Template

import { Component } from '@angular/core';

@Component({
moduleId: module.id,
selector: 'customer',
templateUrl: 'customer.component.html',
styleUrls: ['customer.component.css']
})
export class CustomerComponent {
customer = { id: 100, name: 'John Smith' };
}

Entradas relacionadas: