Built-in Directives
Nima bu?
*ngIf shartli ravishda DOM elementni yaratadi yoki olib tashlaydi (display:none emas). else — shart false bo'lganda ko'rsatiladigan shablon; then — shart true bo'lganda maxsus shablon (kam ishlatiladi). ng-template bilan birga ishlaydi.
Kod misoli
@if (user; as u) {
<p>Xush kelibsiz, {{ u.name }}!</p>
} @else {
<p>Iltimos, tizimga kiring.</p>
}
<!-- Klassik sintaksis (hali qo'llab-quvvatlanadi) -->
<div *ngIf="isAdmin; else guestTemplate">Admin panel</div>
<ng-template #guestTemplate>
<p>Mehmon rejimi</p>
</ng-template>
<ng-container *ngIf="loading; else content">
<app-spinner />
</ng-container>
<ng-template #content>
<app-dashboard [data]="dashboardData" />
</ng-template>
@Component({
selector: 'app-auth-status',
standalone: true,
templateUrl: './auth-status.component.html',
})
export class AuthStatusComponent {
user: { name: string } | null = { name: 'Dilnoza' };
isAdmin = false;
loading = false;
dashboardData = { widgets: 5 };
}
Imtihonda
*ngIf="false"va[hidden]="true"farqi?elsetemplate qanday bog'lanadi?- Angular 17
@ifvs*ngIfafzalliklari?
Yodlash uchun
*ngIf — DOM'dan qo'shadi/oladi; else uchun #ref + ng-template.
Nima bu?
*ngFor massiv yoki iterable bo'ylab takrorlaydi. trackBy — DOM qayta yaratilishini kamaytirish uchun element identifikatori; $index, $first, $last, $even, $odd — loop kontekst o'zgaruvchilari.
Kod misoli
interface Product {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-product-list',
standalone: true,
template: `
<ul>
@for (product of products; track product.id; let i = $index) {
<li [class.alt]="$even">
{{ i + 1 }}. {{ product.name }} — {{ product.price | currency:'UZS' }}
@if ($first) { <span>(birinchi)</span> }
@if ($last) { <span>(oxirgi)</span> }
</li>
} @empty {
<li>Mahsulot topilmadi</li>
}
</ul>
`,
})
export class ProductListComponent {
products: Product[] = [
{ id: 1, name: 'Telefon', price: 3_500_000 },
{ id: 2, name: 'Noutbuk', price: 8_000_000 },
];
trackById(_index: number, item: Product): number {
return item.id;
}
}
Imtihonda
trackBynima uchun kerak?*ngForichida*ngIfqo'yish xatosi va yechimi?@for ... tracksintaksisi qanday ishlaydi?
Yodlash uchun
Har doim track/trackBy ishlat; index emas, stable id tanla.
Nima bu?
[ngClass] elementga dinamik CSS klasslar qo'shadi. Uch usul: string — bitta yoki bir nechta klass; array — klasslar ro'yxati; object — { 'klass-nomi': shart } formatida shartli klasslar.
Kod misoli
@Component({
selector: 'app-status-badge',
standalone: true,
template: `
<!-- Object usuli -->
<span [ngClass]="{
'badge': true,
'badge-success': status === 'active',
'badge-danger': status === 'error',
'badge-warning': status === 'pending'
}">{{ label }}</span>
<!-- Array usuli -->
<span [ngClass]="['badge', sizeClass, isBold ? 'font-bold' : '']">{{ label }}</span>
<!-- String usuli -->
<span [ngClass]="'badge badge-' + status">{{ label }}</span>
<!-- Class binding (alternativa) -->
<span [class.badge-success]="status === 'active'">{{ label }}</span>
`,
styles: [`
.badge { padding: 0.25rem 0.5rem; border-radius: 4px; }
.badge-success { background: #dcfce7; color: #166534; }
.badge-danger { background: #fee2e2; color: #991b1b; }
.badge-warning { background: #fef3c7; color: #92400e; }
`],
})
export class StatusBadgeComponent {
status: 'active' | 'error' | 'pending' = 'active';
label = 'Faol';
sizeClass = 'text-sm';
isBold = true;
}
Imtihonda
[ngClass]va[class.foo]qachon qaysi biri?- Object'da
truebo'lmagan qiymatlar nima qiladi? - Performance: ko'p klass vs bitta computed property?
Yodlash uchun
ngClass — string, array yoki { klass: shart } ob'ekt.
Nima bu?
[ngStyle] elementga dinamik inline style beradi. Ob'ekt ko'rinishida: CSS property nomi → qiymat. [style.prop] alohida property binding ham mumkin. Ko'p style o'zgarishi bo'lsa computed signal/metod afzal.
Kod misoli
@Component({
selector: 'app-progress-bar',
standalone: true,
template: `
<div class="track">
<div
[ngStyle]="{
width: percent + '%',
backgroundColor: barColor,
transition: 'width 0.3s ease'
}"
></div>
</div>
<p>{{ percent }}%</p>
<button type="button" (click)="increase()">Oshirish</button>
`,
styles: [`
.track { height: 8px; background: #e5e7eb; border-radius: 4px; overflow: hidden; }
.track > div { height: 100%; }
`],
})
export class ProgressBarComponent {
percent = 40;
get barColor(): string {
if (this.percent >= 80) return '#22c55e';
if (this.percent >= 50) return '#3b82f6';
return '#f59e0b';
}
increase(): void {
this.percent = Math.min(100, this.percent + 10);
}
}
Imtihonda
[ngStyle]vs[style.width.px]farqi?- CSS property nomlari camelCase yoki kebab-case?
- ngStyle performance muammosi bormi?
Yodlash uchun
ngStyle = { cssProperty: value }; camelCase property nomlari.
Nima bu?
ngSwitch — bitta ifoda qiymatiga qarab bir nechta shablondan birini tanlaydi (JS switch ga o'xshash). *ngSwitchCase — mos keladigan holat; *ngSwitchDefault — hech biri mos kelmasa. Angular 17+ da @switch afzal.
Kod misoli
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
type OrderStatus = 'pending' | 'shipped' | 'delivered' | 'cancelled';
@Component({
selector: 'app-order-status',
standalone: true,
imports: [CommonModule],
template: `
@switch (status) {
@case ('pending') {
<span class="status pending">Kutilmoqda...</span>
}
@case ('shipped') {
<span class="status shipped">Yo'lda</span>
}
@case ('delivered') {
<span class="status delivered">Yetkazildi ✓</span>
}
@default {
<span class="status cancelled">Bekor qilindi</span>
}
}
<!-- Klassik sintaksis -->
<div [ngSwitch]="status">
<p *ngSwitchCase="'pending'">Buyurtma tayyorlanmoqda</p>
<p *ngSwitchCase="'shipped'">Kuryer yo'lda</p>
<p *ngSwitchDefault>Noma'lum holat</p>
</div>
`,
})
export class OrderStatusComponent {
status: OrderStatus = 'shipped';
}
Imtihonda
ngSwitchvs bir nechta*ngIf— qachon switch?*ngSwitchCasebir nechta qiymat qabul qiladimi?@switchtype narrowing qo'llab-quvvatlaydimi?
Yodlash uchun
Switch = bitta qiymat, ko'p holat; default case unutma.
Nima bu?
Angular 17 yangi built-in control flow sintaksisini kiritdi: @if, @for, @switch. Structural directive (*ngIf) o'rniga to'g'ridan-to'g'ri template sintaksisi; @empty, @else if qo'llab-quvvatlanadi; build vaqtida optimallashtiriladi va o'qish osonroq.
Kod misoli
@Component({
selector: 'app-control-flow',
standalone: true,
template: `
@if (user(); as u) {
<h2>{{ u.name }}</h2>
@if (u.role === 'admin') {
<app-admin-panel />
} @else if (u.role === 'editor') {
<app-editor-panel />
} @else {
<app-viewer-panel />
}
} @else {
<app-login />
}
<ul>
@for (item of items(); track item.id; let idx = $index) {
<li>{{ idx + 1 }}. {{ item.title }}</li>
} @empty {
<li>Ro'yxat bo'sh</li>
}
</ul>
@switch (theme()) {
@case ('dark') { <span class="theme-dark">🌙</span> }
@case ('light') { <span class="theme-light">☀️</span> }
@default { <span>Auto</span> }
}
`,
})
export class ControlFlowComponent {
user = () => ({ name: 'Aziza', role: 'admin' as const });
items = () => [{ id: 1, title: 'Angular 17' }, { id: 2, title: 'Signals' }];
theme = () => 'dark' as 'dark' | 'light';
}
Imtihonda
- Migratsiya schematic nomi nima?
@for trackmajburiymi?- Eski
*ngIfhali ishlatiladimi?
Yodlash uchun
v17+ control flow: @if, @for track, @switch — yangi standart.
