Template sintaksisi
Angular template'lari HTML kengaytmasi — binding, event, ref va xavfsiz null tekshiruvi shu yerda boshlanadi. Bu guruh klassik template sintaksisining intervyuda eng ko'p so'raladigan qismlarini qamrab oladi.
Template reference variable (#ref)
Nima bu?
Template reference variable (#name yoki ref-name) template ichidagi DOM element, komponent yoki directive'ga havola beradi. U orqali input qiymatini o'qish, form validatsiyasini tekshirish yoki child komponent metodini chaqirish mumkin. exportAs bilan directive ref beriladi — masalan #ctrl="ngModel".
Kod misoli
<input #searchInput type="text" placeholder="Qidirish..." />
<button type="button" (click)="search(searchInput.value)">Qidir</button>
<p>Qiymat: {{ searchInput.value }}</p>
<form #loginForm="ngForm">
<input name="email" ngModel required #emailCtrl="ngModel" />
@if (emailCtrl.invalid && emailCtrl.touched) {
<span class="error">Email majburiy</span>
}
<button type="submit" [disabled]="loginForm.invalid">Kirish</button>
</form>
import { Component, ViewChild, ElementRef } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-search',
standalone: true,
imports: [FormsModule],
templateUrl: './search.component.html',
})
export class SearchComponent {
@ViewChild('searchInput') searchInputRef!: ElementRef<HTMLInputElement>;
@ViewChild('loginForm') loginFormRef!: NgForm;
search(query: string): void {
console.log('Qidiruv:', query.trim());
}
focusSearch(): void {
this.searchInputRef.nativeElement.focus();
}
}
Imtihonda
#refva#ref="ngModel"farqi nima?- Template ref komponent klassida qanday ishlatiladi (
@ViewChild)? - Bir elementda bir nechta ref bo'ladimi?
Yodlash uchun
#ref — template ichida elementga nom; exportAs bilan directive ref beriladi.
Safe navigation (?.) — null check zanjiri
Nima bu?
Safe navigation operator (?.) — zanjir bo'ylab null yoki undefined uchrasa xato o'rniga undefined qaytaradi. Chuqur nested ob'ektlarda (user?.profile?.address?.city) har bosqichda null tekshiruvi qilish shart emas. ?? (nullish coalescing) bilan default qiymat berish mumkin.
Kod misoli
interface Address {
city?: string;
zip?: string;
}
interface Profile {
address?: Address;
phone?: string;
}
interface User {
profile?: Profile;
}
@Component({
selector: 'app-user-card',
standalone: true,
template: `
<!-- Safe navigation zanjir -->
<p>Shahar: {{ user?.profile?.address?.city ?? 'Noma\'lum' }}</p>
<p>Telefon: {{ user?.profile?.phone ?? '—' }}</p>
<!-- Method chaqirish ham xavfsiz -->
<p>Format: {{ user?.profile?.address?.zip?.toUpperCase() ?? '—' }}</p>
<!-- @if bilan birga — eng xavfsiz pattern -->
@if (user?.profile?.address?.city; as city) {
<p>Manzil: {{ city }}</p>
}
`,
})
export class UserCardComponent {
user: User | null = {
profile: { address: { city: 'Toshkent' } },
};
}
Imtihonda
user?.namevauser && user.namefarqi nima??.va??qachon birga ishlatiladi?- Strict null checks bilan template xatolari qanday aniqlanadi?
Yodlash uchun
?. — null/undefined bo'lsa to'xtaydi; ?? — faqat null/undefined uchun default.
$event, $any() — template ichida
Nima bu?
$event — template event handler'ida DOM yoki custom event ob'ektini ifodalaydi. (click)="onClick($event)" — MouseEvent, (input)="onInput($event)" — Event with target. $any(expr) — template'da vaqtinchalik type cast; TypeScript strict tekshiruvini chetlab o'tadi. Production kodda kam ishlatiladi, lekin legacy API yoki dynamic property uchun kerak bo'ladi.
Kod misoli
@Component({
selector: 'app-event-demo',
standalone: true,
template: `
<!-- $event — DOM event -->
<button type="button" (click)="handleClick($event)">Bos</button>
<!-- Input event — target orqali qiymat -->
<input type="range" min="0" max="100"
[value]="volume"
(input)="volume = +$any($event.target).value" />
<!-- Custom Output event -->
<app-rating (rated)="onRated($event)" />
<!-- $any() — dynamic/legacy property -->
<p>{{ $any(config).legacyTitle ?? config.title }}</p>
`,
})
export class EventDemoComponent {
volume = 50;
config = { title: 'Yangi sarlavha' };
handleClick(event: MouseEvent): void {
event.preventDefault();
console.log('Koordinata:', event.clientX, event.clientY);
}
onRated(score: number): void {
console.log('Baho:', score);
}
}
// Child komponent — custom $event
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-rating',
standalone: true,
template: `
@for (star of [1, 2, 3, 4, 5]; track star) {
<button type="button" (click)="select(star)">★</button>
}
`,
})
export class RatingComponent {
@Output() rated = new EventEmitter<number>();
select(score: number): void {
this.rated.emit(score);
}
}
Imtihonda
$eventni inline expression'da qanday ishlatish mumkin?$any()qachon xavfli va nima uchun?- Custom
@Outputevent$eventsifatida qanday keladi?
Yodlash uchun
$event — handler'ga kelgan event; $any() — template type cast (ehtiyotkorlik bilan).
ng-template bilan *ngIf else pattern
Nima bu?
*ngIf structural directive shartli render qiladi. else bloki uchun ng-template #ref bilan bog'lanadi; then bloki ham ixtiyoriy template ref orqali beriladi. Microsyntax (*ngIf="x; else y") aslida <ng-template [ngIf]="x"> ga aylantiriladi. Angular 17+ da @if/@else tavsiya etiladi, lekin legacy kod va murakkab pattern'larda ng-template hali ham muhim.
Kod misoli
<!-- Klassik *ngIf else -->
<div *ngIf="user; else loadingTpl">
<h2>{{ user.name }}</h2>
<p *ngIf="user.isAdmin; else guestTpl">Admin panel</p>
</div>
<ng-template #loadingTpl>
<p class="spinner">Yuklanmoqda...</p>
</ng-template>
<ng-template #guestTpl>
<p>Mehmon rejimi</p>
</ng-template>
<!-- then + else -->
<ng-container *ngIf="isLoggedIn; then dashboard; else loginPage"></ng-container>
<ng-template #dashboard>
<app-dashboard />
</ng-template>
<ng-template #loginPage>
<app-login-form />
</ng-template>
import { Component } from '@angular/core';
import { NgIf } from '@angular/common';
interface User {
name: string;
isAdmin: boolean;
}
@Component({
selector: 'app-profile',
standalone: true,
imports: [NgIf],
templateUrl: './profile.component.html',
})
export class ProfileComponent {
user: User | null = null;
isLoggedIn = false;
ngOnInit(): void {
setTimeout(() => {
this.user = { name: 'Ali', isAdmin: true };
this.isLoggedIn = true;
}, 1000);
}
}
<!-- Zamonaviy ekvivalent — Angular 17+ -->
@if (user) {
<h2>{{ user.name }}</h2>
@if (user.isAdmin) {
<p>Admin panel</p>
} @else {
<p>Mehmon rejimi</p>
}
} @else {
<p class="spinner">Yuklanmoqda...</p>
}
Imtihonda
*ngIf="a; else b"qanday DOM struktura hosil qiladi?ng-containervang-templatefarqi?@if/@elsega migratsiya qilishda nimalarga e'tibor beriladi?
Yodlash uchun
*ngIf → ng-template; else/then — #ref bilan bog'lanadi.
ng-container — DOM element qo'shmasdan
Nima bu?
<ng-container> — virtual konteyner: DOM'ga real element qo'shmasdan structural directive yoki template grouping qiladi. CSS layout buzilmaydi (masalan, flex/grid ichida ortiqcha <div> bo'lmaydi). Bir nechta elementni shart yoki loop ichiga olish, *ngIf else/then ni ulash uchun ishlatiladi.
Kod misoli
<!-- Flex layout buzilmasin -->
<ul class="toolbar">
<li><a routerLink="/">Bosh</a></li>
<ng-container *ngIf="isAdmin">
<li><a routerLink="/admin">Admin</a></li>
<li><a routerLink="/reports">Hisobot</a></li>
</ng-container>
<li><a routerLink="/profile">Profil</a></li>
</ul>
<!-- Bir nechta elementni @if ichida (Angular 17+) -->
<div class="card">
<ng-container>
@if (product.discount) {
<span class="badge">-{{ product.discount }}%</span>
<span class="old-price">{{ product.price | currency:'UZS' }}</span>
}
</ng-container>
<span class="price">{{ product.finalPrice | currency:'UZS' }}</span>
</div>
<!-- ng-template ni ulash — ng-container orqali -->
<ng-container *ngTemplateOutlet="actionButtons; context: { item: row }" />
import { Component } from '@angular/core';
import { NgIf, NgTemplateOutlet, CurrencyPipe } from '@angular/common';
@Component({
selector: 'app-product-card',
standalone: true,
imports: [NgIf, NgTemplateOutlet, CurrencyPipe],
templateUrl: './product-card.component.html',
})
export class ProductCardComponent {
isAdmin = true;
product = {
price: 100_000,
discount: 15,
finalPrice: 85_000,
};
row = { id: 1, name: 'Mahsulot' };
}
Imtihonda
ng-containervadivo'rniga ishlatish farqi?*ngTemplateOutletnima uchun kerak?@ifbilanng-containerhali ham kerakmi?
Yodlash uchun
ng-container — DOM'siz wrapper; layout va grouping uchun.
