Angular forms / data binding#
whole tree will be scanned for changesTwo-way binding#
- was used in AngularJS 1,x, now replaced with one way bindings via property and event bindung
- can be still used with <input [(ngModel)]="time.hours">
- app.module.ts need to imports: [FormsModule]
- <any [prop]="value" (propChange)="value=$event"></any> is equivalent to <any [(prop)]="value"></any>
- ngOnChange(changes: SimpleChanges) {...} (is also called initially, you can ignore ngOnInit())
- import {SimpleChanges} from '@angular/core';
Event binding #
- (<eventName>)='<method/statement>'
- <button (click)="time.hours=time.hours+1">Plus</button>
- canonical: <button on-click=...
- pseudo events (keydown.enter) (keydown.control.enter) ...
- $event gives access to event data (DOM) like $event.target.value
Interpolation #
- {{property}}
- <div>Time: {{getTime()}}</div>
property binding #
- [<DOM-attrib>]='instance.property'
- <input [value]="time?.hours"/> = safe-navigation operator (time!=null|undefined)
- <input bind-value="time?.hours"/> = canonical binding (equivalent to above)
- [DOM-API|https://developer.mozilla.org/en-US/docs/Web/API/] (html attributes vs dom)
- <td [attr.colspan]="calculateColSpan()"></td> = set atribute directly
- <div [class.alert]="temperatue>100">...</div> = set class directly
- <div [style.font-size.px]="calculateFontSize()">{{temperature}}</div>
Local DOM variables in html #
- #name
- <input #minutes ...> in class available like minutes.focus() (DOM)
- canonical: <input ref-minutes ...>
- @Input = input variable to place into DOM without iteration, iteration through component tag and * @Output
Microsyntax (*)#
- *ngXXX manipulates structure of DOM tree
- ngFor = <template ngFor let-value [ngForOf]="values>
- ngIf = <template [ngIf]="isVisible">
Input / Output#
- @Input()
- ngOnInit(){...}
- canonical: @Component({ inputs: ['time',...] )}
- @Output()
- EventEmitter.emit(value) (Observable, part of RxJS=reactive/async)
- register for event in other component: (timeChange)="onTimeChanged($event)" ($event=emitted value)
- canonical: @Component({ outputs: ['time',...] )}
Children#
- @ViewChildren