Reference · Frontend · Angular 16
Angular 16 dasar untuk developer React
Ringkasan satu halaman. Dari Lesson 0013. Semua sintaks versi 16 (tanpa @if/@for v17).
Component
@Component({ selector: 'app-product-card', templateUrl: './x.html', styleUrls: ['./x.css'] })
export class ProductCardComponent {
@Input() product!: Product; // parent → child (props)
@Output() deleted = new EventEmitter<number>(); // child → parent (callback prop)
}
NgModule
| Array | Isi | Padanan |
|---|---|---|
declarations | Component/directive/pipe milik module ini | file component di folder fitur |
imports | Module lain (FormsModule, HttpClientModule, CommonModule) | import paket npm |
providers | Service untuk DI | Context Provider / NestJS providers |
bootstrap | Root component (AppComponent) | createRoot().render(<App/>) |
Standalone component: standalone: true + imports: [...] di @Component, tanpa NgModule; bootstrap lewat bootstrapApplication(AppComponent). Jangan dimasukkan ke declarations. Default ng new v16 masih NgModule (kecuali --standalone).
Binding
| Sintaks | Nama | Arah | JSX |
|---|---|---|---|
{{ x }} | Interpolation | class → view | {x} |
[prop]="x" | Property binding | class → elemen | prop={x} |
(event)="f($event)" | Event binding | elemen → class | onEvent={f} |
[(ngModel)]="x" | Two-way (butuh FormsModule) | dua arah | value + onChange |
Two-way untuk component sendiri: @Input() size + @Output() sizeChange → [(size)]="x".
Structural directive
<p *ngIf="loading; else done">Memuat…</p> <ng-template #done>…</ng-template>
<li *ngFor="let p of products; trackBy: trackById; let i = index">{{ i }}. {{ p.name }}</li>
<div [ngSwitch]="status"><span *ngSwitchCase="'active'">Aktif</span><span *ngSwitchDefault>–</span></div>
<ng-container *ngIf="isAdmin">…</ng-container> <!-- seperti Fragment -->
*= singkatan untuk<ng-template>. Hanya satu structural directive per elemen; gabungkan dengan<ng-container>.trackBy≈keydi React.
Lifecycle Hook
| Hook | Kapan | Untuk | React |
|---|---|---|---|
constructor | class dibuat | inject dependency saja | badan function |
ngOnChanges | sebelum ngOnInit + tiap input berubah | reaksi ke @Input (SimpleChanges) | useEffect(f, [dep]) |
ngOnInit | sekali, setelah ngOnChanges pertama | ambil data awal | useEffect(f, []) |
ngOnDestroy | tepat sebelum dihancurkan | unsubscribe, lepas handler | cleanup useEffect |
Jebakan interview
- Fetch data di constructor → pindahkan ke
ngOnInit. - "Can't bind to 'ngModel'" →
FormsModulebelum ada diimports. - Module lain dimasukkan ke
declarations→ seharusnyaimports. - Menjawab dengan
@if/@for→ itu Angular 17.
Sumber: NgModules · Standalone · Binding · Inputs/Outputs · Structural directives · Lifecycle hooks (dokumentasi Angular v16)