Asosiy matnga o'tish
ITIT Interview
Angular

Komponentlar va shablonlar

Komponent tuzilishi, data binding turlari, input va output, model bilan ikki tomonlama bog'lash, content projection, template reference va hayot sikli hooklari.

O'rganildi: 0 / 5
Progress

Komponent tuzilishi

user-card.component.ts
import { Component, input, output } from '@angular/core';

export interface User {
  id: number;
  name: string;
  email: string;
}

@Component({
  selector: 'app-user-card',
  templateUrl: './user-card.component.html',
  styleUrl: './user-card.component.css',
})
export class UserCardComponent {
  user = input.required<User>();          // ota komponentdan keladi
  showEmail = input(false);               // standart qiymat bilan
  selected = output<number>();            // otaga hodisa

  select() {
    this.selected.emit(this.user().id);
  }
}
user-card.component.html
<div class="card">
  <h3>{{ user().name }}</h3>
  @if (showEmail()) {
    <p>{{ user().email }}</p>
  }
  <button (click)="select()">Tanlash</button>
</div>
Ota komponent shabloni
<app-user-card [user]="currentUser" [showEmail]="true" (selected)="onSelect($event)" />

Signal asosidagi input()/output() — zamonaviy API. Eski kodda dekoratorlar uchraydi:

@Input({ required: true }) user!: User;
@Output() selected = new EventEmitter<number>();

Stillar standart holda inkapsulyatsiya qilinadi (emulated): komponent CSS'i faqat shu komponentga ta'sir qiladi.

Data binding turlari

SintaksisYo'nalishMisol
InterpolatsiyaKomponent → shablon{{ user().name }}
Property bindingKomponent → element[disabled]="isLoading()"
Event bindingElement → komponent(click)="save()"
Ikki tomonlamaIkkalasi[(ngModel)]="name"
<img [src]="avatarUrl()" [alt]="user().name" />
<button [class.active]="isActive()" [style.width.px]="width()">OK</button>
<input (keyup.enter)="search($event)" />
<td [attr.colspan]="span">...</td>

model() bilan ikki tomonlama bog'lash

rating.component.ts
@Component({
  selector: 'app-rating',
  template: `
    @for (star of [1, 2, 3, 4, 5]; track star) {
      <button (click)="value.set(star)">{{ star <= value() ? '★' : '☆' }}</button>
    }
  `,
})
export class RatingComponent {
  value = model(0);      // input + output birga
}
<app-rating [(value)]="productRating" />
<!-- aslida: [value]="productRating" (valueChange)="productRating = $event" -->

Content projection

Ota komponent bola ichiga kontent joylaydi (React'dagi children, Vue'dagi slotlar):

card.component.ts
@Component({
  selector: 'app-card',
  template: `
    <div class="card">
      <header><ng-content select="[card-title]" /></header>
      <ng-content />
    </div>
  `,
})
export class CardComponent {}
<app-card>
  <h2 card-title>Profil</h2>
  <p>Asosiy kontent</p>
</app-card>

Template reference va viewChild

<input #searchInput />
<button (click)="searchInput.focus()">Fokus</button>
import { Component, ElementRef, viewChild, afterNextRender } from '@angular/core';

export class SearchComponent {
  input = viewChild.required<ElementRef<HTMLInputElement>>('searchInput');

  constructor() {
    afterNextRender(() => this.input().nativeElement.focus());
  }
}

Hayot sikli hooklari

HookQachon
constructorKlass yaratilganda: faqat DI, input'lar hali yo'q
ngOnChangesInput qiymati o'zgarganda (dekorator input'lari uchun)
ngOnInitBirinchi input'lar o'rnatilgandan keyin bir marta: boshlang'ich yuklash
ngAfterViewInitKomponent va bolalari render bo'lgandan keyin
ngOnDestroyKomponent yo'q qilinishidan oldin: tozalash
afterNextRender / afterEveryRenderDOM bilan ishlash (faqat brauzerda)
export class ClockComponent implements OnInit, OnDestroy {
  private timer?: ReturnType<typeof setInterval>;

  ngOnInit() {
    this.timer = setInterval(() => this.now.set(new Date()), 1000);
  }

  ngOnDestroy() {
    clearInterval(this.timer);
  }
}

Zamonaviy alternativa: inject(DestroyRef).onDestroy(() => ...).

Intervyu savollari

Ushbu sahifada