Components
Contents
Definition
- Building blocks of the angular app.
- Every component consists of three sections
TSfile → for logicHTMLfile → HTML templateCSSfile → styles for the template
@Component
TestComponent
@Component({
selector : 'test',
templateUrl : './test.component.html',
styleUrls : ['./test.component.css']
})
selectordefines html like tag we can use in pagestemplateUrldefines path for html templatestyleUrlsdefines css files to be use for the html template
HTML Template
- Looks like a normal html but it is NOT
- Syntax extended to allow
- Custom component selectors
<nav-bar></nav-bar> - Data binding
{{ count }} - Directives
*ngIf
- Custom component selectors
- Browser CANNOT understand bare template. It has to interpreted by angular framework first
Data binding
- Interpolation
- html
{{ count }} - ts
count : number = 5
- html
- Property Binding
<a [title] = "link_title">
- Event Binding
<button (click) = "calculate()">
- Two-Way Binding
<input [(ngModel)] = "userInput">
Read Data Binding Section
Directives
- Structural Directives
*ngIf*ngFor- `
*ngSwitch
- Attribute Directives
ngClassngStyle
Read Directives Section
Life Cycle of Components
Component has a life cycle managed by Angular and provides life cycle hooks to act when they occur
note
NOTE: Constructor() is called before ngOnInit()
Order:
Constructor()ngOnChanges()ngOnInit()ngOnDestroy()
Input and Output
@Input
Child.TS
@Input('count') public count: number;
Parent.HTML
<div>
<child [count] = 5></child>
</div>
Child.HTML
<div>
{{ count }}
</div>
@Output
Child.TS
@Output('passCount') public countEmitter: EventEmitter<number> = new Emitter();
this.countEmitter.next(5);
Parent.HTML
<div>
<child (passCount) = "receiveCount($event)"></child>
<p>{{ count }}</p>
</div>
Parent.TS
count: number;
receiveCount(count: number){
this.count = count;
}