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

ArrayIsiPadanan
declarationsComponent/directive/pipe milik module inifile component di folder fitur
importsModule lain (FormsModule, HttpClientModule, CommonModule)import paket npm
providersService untuk DIContext Provider / NestJS providers
bootstrapRoot 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

SintaksNamaArahJSX
{{ x }}Interpolationclass → view{x}
[prop]="x"Property bindingclass → elemenprop={x}
(event)="f($event)"Event bindingelemen → classonEvent={f}
[(ngModel)]="x"Two-way (butuh FormsModule)dua arahvalue + 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 -->

Lifecycle Hook

HookKapanUntukReact
constructorclass dibuatinject dependency sajabadan function
ngOnChangessebelum ngOnInit + tiap input berubahreaksi ke @Input (SimpleChanges)useEffect(f, [dep])
ngOnInitsekali, setelah ngOnChanges pertamaambil data awaluseEffect(f, [])
ngOnDestroytepat sebelum dihancurkanunsubscribe, lepas handlercleanup useEffect

Jebakan interview

  1. Fetch data di constructor → pindahkan ke ngOnInit.
  2. "Can't bind to 'ngModel'" → FormsModule belum ada di imports.
  3. Module lain dimasukkan ke declarations → seharusnya imports.
  4. Menjawab dengan @if/@for → itu Angular 17.

Sumber: NgModules · Standalone · Binding · Inputs/Outputs · Structural directives · Lifecycle hooks (dokumentasi Angular v16)