> For the complete documentation index, see [llms.txt](https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/data-binding-va-direktivalar.md).

# Data Binding va Direktivalar

### Mundarija

1. **Data Binding turlari:**
   * Interpolation: `{{ variable }}`
   * Property Binding: `[property]="value"`
   * Event Binding: `(event)="handler()"`
   * Two-way Data Binding: `[(ngModel)]="variable"`
2. **Direktivalar:**
   * Structural directives: `*ngIf`, `*ngFor`, `*ngSwitch`.
   * Attribute directives: `ngClass`, `ngStyle`
   * Custom directives yaratish
3. **Control flow:** `@if` , `@for` , `@switch`

***

### 1. Data Binding nima?

**Data Binding** - bu component class (TypeScript) va template (HTML) o'rtasida ma'lumotlarni avtomatik sinxronlash mexanizmidir. Ya’ni sodda tilda aytganda componentdagi ma’lumotni templateda chiqarish, templatedan turib biror harakat haqida componentni xabardor qilish va shuningdek templatedan turib componentdagi o’sha ma’lumotga o’zgartirish kirita olish tushiniladi.

#### 1.1 Interpolation (Interpolyatsiya)

Interpolation - bu componentdagi o'zgaruvchilarni HTML ga chiqarish usuli.

**Sintaksis:** `{{ variable }}`

**Misol:**

```tsx
// calculator.component.ts
export class CalculatorComponent {
  title = 'Matematika Kalkulyatori';
  result = 0;
  userName = 'Utamuratov';
}
```

```html
<!-- calculator.component.html -->
<h1>{{ title }}</h1>
<p>Natija: {{ result }}</p>
<p>Foydalanuvchi: {{ userName }}</p>
```

**Natija:**

```
Matematika Kalkulyatori
Natija: 0
Foydalanuvchi: Sardor
```

**Quyidagicha ifodalarni ham yozsa bo’ladi:**

```html
<p>Yig'indi: {{ 5 + 3 }}</p>
<p>Ism: {{ userName.toUpperCase() }}</p>
<p>Natija: {{ result * 2 }}</p>
```

***

#### 1.2 Property Binding

Property Binding - bu HTML elementining xususiyatiga (property) qiymat berish usuli.

**Sintaksis:** `[property]="value"`

**Misol:**

```tsx
export class CalculatorComponent {
  imageUrl = 'assets/calculator.png';
  isDisabled = false;
  inputValue = 10;
  buttonColor = 'blue';
}
```

```html
<!-- Rasm manbai -->
<img [src]="imageUrl" alt="Kalkulyator">

<!-- Tugma holati -->
<button [disabled]="isDisabled">Hisoblash</button>

<!-- Input qiymati -->
<input type="number" [value]="inputValue">

<!-- Style -->
<div [style.color]="buttonColor">Matn</div>

<!-- Class -->
<div [class.active]="isDisabled">Element</div>
```

**Property Binding vs Interpolation:**

```html
<!-- **Property Binding** -->
<img [src]="imageUrl">

<!-- **Interpolation** -->
<img src="{{ imageUrl }}">
```

***

#### 1.3 Event Binding

Event Binding - bu HTML elementidagi hodisalarni (click, input, change va h.k.) komponent metodlariga bog'lash.

**Sintaksis:** `(event)="handler()"`

**Misol:**

```tsx
export class CalculatorComponent {
  result = 0;

  calculateSum() {
    this.result = 10 + 5;
    console.log('Hisoblandi:', this.result);
  }

  onInputChange(event: any) {
    console.log('Input qiymati:', event.target.value);
  }

  showMessage(message: string) {
    alert(message);
  }
}
```

```html
<!-- Click hodisasi -->
<button (click)="calculateSum()">Hisoblash</button>

<!-- Input hodisasi -->
<input (input)="onInputChange($event)">

<!-- Parametr bilan -->
<button (click)="showMessage('Salom!')">Ko'rsatish</button>

<!-- Multiple events -->
<input
  (focus)="onFocus()"
  (blur)="onBlur()"
  (keyup)="onKeyUp($event)">
```

**$event** - bu hodisa haqida to'liq ma'lumot:

```tsx
onKeyUp(event: KeyboardEvent) {
  console.log('Bosilgan tugma:', event.key);
  if (event.key === 'Enter') {
    this.calculateSum();
  }
}
```

***

#### 1.4 Two-Way Data Binding

Two-Way Data Binding - bu ma'lumotni component va template o'rtasida ikki tomonga ham sinxronlash.

**Sintaksis:** `[(ngModel)]="variable"`

{% hint style="info" %}
**Muhim**

`ngModel` ishlatish uchun `FormsModule` ni import qilish kerak!
{% endhint %}

```tsx
@Component({
	imports: [
    FormsModule  // ← Qo'shish kerak
	],
	...
})
export class CalculatorComponent {
  num1: number = 0;
  num2: number = 0;
  studentName: string = '';
}
```

```html
<div>
  <label>Birinchi son:</label>
  <input type="number" [(ngModel)]="num1">
  <p>Siz kiritdingiz: {{ num1 }}</p>
</div>

<div>
  <label>Ikkinchi son:</label>
  <input type="number" [(ngModel)]="num2">
  <p>Siz kiritdingiz: {{ num2 }}</p>
</div>

<div>
  <label>Ismingiz:</label>
  <input type="text" [(ngModel)]="studentName">
  <p>Salom, {{ studentName }}!</p>
</div>

<p>Yig'indi: {{ num1 + num2 }}</p>
```

**Qanday ishlaydi?**

`[(ngModel)]` aslida quyidagicha ishlaydi:

```html
<!-- Two-way binding -->
<input [(ngModel)]="num1">

<!-- Bu quyidagiga teng: -->
<input
  [ngModel]="num1"
  (ngModelChange)="num1 = $event">
```

{% embed url="<https://youtu.be/Bl2IpJOBl0E?si=4Nn6on0Gxyq0pyLk>" %}

***

### 2. Direktivalar (Directives)

**Direktiva** - bu HTML elementlarining ko'rinishi yoki xatti-harakatini o'zgartiruvchi Angular buyruqlari.

#### 2.1 Structural Directives

Strukturaviy direktivalar HTML DOM ni o'zgartiradi (element qo'shadi yoki olib tashlaydi). Bunga misollar: `*ngIf` , `*ngFor` , `*ngSwitch`

#### 2.1.1 \*ngIf

**Sintaksis:** `*ngIf="condition"`

```tsx
export class CalculatorComponent {
  result: number = 0;
  showResult: boolean = false;
  isLoggedIn: boolean = true;
  score: number = 85;
}
```

```html
<!-- Oddiy *ngIf -->
<div *ngIf="showResult">
  <p>Natija: {{ result }}</p>
</div>

<!-- *ngIf with else -->
<div *ngIf="isLoggedIn; else notLoggedIn">
  <p>Xush kelibsiz!</p>
</div>
<ng-template #notLoggedIn>
  <p>Iltimos, tizimga kiring</p>
</ng-template>

<!-- *ngIf with then and else -->
<div *ngIf="score >= 60; then passed; else failed"></div>
<ng-template #passed>
  <p class="success">Test topshirdingiz! ✓</p>
</ng-template>
<ng-template #failed>
  <p class="error">Afsuski, test topshirmadingiz ✗</p>
</ng-template>

<!-- Multiple conditions -->
<div *ngIf="isLoggedIn && score > 50">
  <p>Siz o'tayapsiz!</p>
</div>

```

#### 2.1.2 \*ngFor

**Sintaksis:** `*ngFor="let item of items"`

```tsx
export class CalculatorComponent {
  numbers: number[] = [1, 2, 3, 4, 5];

  students = [
    { id: 1, name: 'Ali', score: 85 },
    { id: 2, name: 'Vali', score: 92 },
    { id: 3, name: 'Sami', score: 78 }
  ];

  history: string[] = [
    '5 + 3 = 8',
    '10 - 4 = 6',
    '7 * 2 = 14'
  ];
}
```

```html
<!-- Oddiy ro'yxat -->
<ul>
  <li *ngFor="let num of numbers">
    {{ num }}
  </li>
</ul>

<!-- Index bilan -->
<ul>
  <li *ngFor="let item of history; let i = index">
    {{ i + 1 }}. {{ item }}
  </li>
</ul>

<!-- Murakkab obyektlar -->
<div *ngFor="let student of students">
  <h3>{{ student.name }}</h3>
  <p>Ball: {{ student.score }}</p>
</div>

<!-- Qo'shimcha o'zgaruvchilar -->
<div *ngFor="let student of students;
             let i = index;
             let isFirst = first;
             let isLast = last;
             let isEven = even;
             let isOdd = odd">

  <p [class.first]="isFirst">
    {{ i + 1 }}. {{ student.name }}
    <span *ngIf="isFirst">(Birinchi)</span>
    <span *ngIf="isLast">(Oxirgi)</span>
  </p>
</div>
```

#### 2.1.3 \*ngSwitch

**Sintaksis:** `[ngSwitch]` va `*ngSwitchCase`

```tsx
export class CalculatorComponent {
  operation: string = 'add';
  grade: string = 'B';
  dayNumber: number = 3;
}
```

```html
<!-- Operatsiya bo'yicha -->
<div [ngSwitch]="operation">
  <p *ngSwitchCase="'add'">Qo'shish operatsiyasi</p>
  <p *ngSwitchCase="'subtract'">Ayirish operatsiyasi</p>
  <p *ngSwitchCase="'multiply'">Ko'paytirish operatsiyasi</p>
  <p *ngSwitchCase="'divide'">Bo'lish operatsiyasi</p>
  <p *ngSwitchDefault>Operatsiya tanlanmagan</p>
</div>

<!-- Baho bo'yicha -->
<div [ngSwitch]="grade">
  <p *ngSwitchCase="'A'" class="excellent">A'lo!</p>
  <p *ngSwitchCase="'B'" class="good">Yaxshi!</p>
  <p *ngSwitchCase="'C'" class="average">O'rtacha</p>
  <p *ngSwitchDefault class="poor">Yaxshilash kerak</p>
</div>

<!-- Kun bo'yicha -->
<div [ngSwitch]="dayNumber">
  <p *ngSwitchCase="1">Dushanba</p>
  <p *ngSwitchCase="2">Seshanba</p>
  <p *ngSwitchCase="3">Chorshanba</p>
  <p *ngSwitchCase="4">Payshanba</p>
  <p *ngSwitchCase="5">Juma</p>
  <p *ngSwitchCase="6">Shanba</p>
  <p *ngSwitchCase="7">Yakshanba</p>
</div>

```

***

#### 2.2 Attribute Directives (Atribut direktivalari)

Atribut direktivalari elementning ko'rinishini yoki xatti-harakatini o'zgartiradi (DOM ga yangi element qo'shmaydi yoki olib ham tashlamaydi).

#### 2.2.1 ngClass - Dinamik class qo'shish

```tsx
export class CalculatorComponent {
  isActive = true;
  isHighlighted = false;
  currentClass = 'primary';

  score = 85;

  getClasses() {
    return {
      'active': this.isActive,
      'highlighted': this.isHighlighted,
      'primary': this.currentClass === 'primary'
    };
  }
}
```

```html
<!-- String bilan -->
<div [ngClass]="'btn btn-primary'">Tugma</div>

<!-- O'zgaruvchi bilan -->
<div [ngClass]="currentClass">Element</div>

<!-- Array bilan -->
<div [ngClass]="['btn', 'btn-large', 'active']">Tugma</div>

<!-- Object bilan (eng ko'p ishlatiladigan) -->
<div [ngClass]="{
  'active': isActive,
  'highlighted': isHighlighted,
  'disabled': !isActive
}">
  Element
</div>

<!-- Metod bilan -->
<div [ngClass]="getClasses()">Element</div>

<!-- Shartli class -->
<div [ngClass]="score >= 60 ? 'passed' : 'failed'">
  Ball: {{ score }}
</div>

<!-- Multiple classes with conditions -->
<div [ngClass]="{
  'bg-success': score >= 90,
  'bg-warning': score >= 60 && score < 90,
  'bg-danger': score < 60
}">
  Natija
</div>

```

#### 2.2.2 ngStyle - Dinamik style qo'shish

```tsx
export class CalculatorComponent {
  fontSize = 16;
  textColor = 'blue';
  isLarge = true;

  backgroundColor = '#f0f0f0';

  getStyles() {
    return {
      'font-size': this.fontSize + 'px',
      'color': this.textColor,
      'font-weight': this.isLarge ? 'bold' : 'normal'
    };
  }
}
```

```html
<!-- Oddiy style -->
<p [style.color]="textColor">Matn</p>
<p [style.font-size.px]="fontSize">Matn</p>

<!-- Object bilan -->
<div [ngStyle]="{
  'color': textColor,
  'font-size': fontSize + 'px',
  'background-color': backgroundColor
}">
  Element
</div>

<!-- Metod bilan -->
<div [ngStyle]="getStyles()">Element</div>

<!-- Shartli style -->
<div [ngStyle]="{
  'color': score >= 60 ? 'green' : 'red',
  'font-weight': score >= 90 ? 'bold' : 'normal'
}">
  Ball: {{ score }}
</div>

<!-- Multiple styles -->
<div [ngStyle]="{
  'width': '100%',
  'height': '200px',
  'border': '1px solid #ccc',
  'padding': '20px',
  'margin': '10px 0'
}">
  Container
</div>
```

***

### 3. Angular 17+ Control Flow (Yangi Sintaksis)

Angular 17 versiyasidan boshlab yangi, soddaroq Control Flow sintaksisi kiritildi. Bu eski `*ngIf`, `*ngFor` va `*ngSwitch` ni almashtiradi.

#### 3.1 @if

**Eski usul:**

```html
<div *ngIf="isLoggedIn">Xush kelibsiz!</div>
```

**Yangi usul:**

```html
@if (isLoggedIn) {
  <div>Xush kelibsiz!</div>
}
```

#### @if with @else

```tsx
export class CalculatorComponent {
  result: number = 0;
  isPositive: boolean = true;
  score: number = 75;
}
```

```html
<!-- Oddiy @if -->
@if (result !== 0) {
  <p>Natija: {{ result }}</p>
}

<!-- @if with @else -->
@if (isPositive) {
  <p class="success">Musbat son ✓</p>
} @else {
  <p class="error">Manfiy son ✗</p>
}

<!-- @if with @else if -->
@if (score >= 90) {
  <p class="grade-a">A'lo! (A)</p>
} @else if (score >= 75) {
  <p class="grade-b">Yaxshi! (B)</p>
} @else if (score >= 60) {
  <p class="grade-c">Qoniqarli (C)</p>
} @else {
  <p class="grade-f">Yaxshilash kerak (F)</p>
}

<!-- Murakkab shartlar -->
@if (isLoggedIn && score > 50) {
  <div class="dashboard">
    <h2>Sizning natijalaringiz</h2>
    <p>Ball: {{ score }}</p>
  </div>
}
```

#### 3.2 @for

**Eski usul:**

```html
<div *ngFor="let item of items">{{ item }}</div>
```

**Yangi usul:**

```html
@for (item of items; track item) {
  <div>{{ item }}</div>
}
```

{% hint style="info" %}
**Muhim**

`track` majburiy! Bu Angular ga qaysi elementni kuzatishni aytadi. Bu haqida keyinchalik chuqurroq o’rganib olsangiz bo’ladi
{% endhint %}

```tsx
export class CalculatorComponent {
  numbers = [1, 2, 3, 4, 5];

  students = [
    { id: 1, name: 'Ali', score: 85 },
    { id: 2, name: 'Vali', score: 92 },
    { id: 3, name: 'Sami', score: 78 }
  ];

  history: string[] = [];
}
```

```html
<!-- Oddiy array -->
@for (num of numbers; track num) {
  <p>Raqam: {{ num }}</p>
}

<!-- Index bilan -->
@for (num of numbers; track num; let i = $index) {
  <p>{{ i + 1 }}. {{ num }}</p>
}

<!-- Obyektlar bilan (id bo'yicha track) -->
@for (student of students; track student.id) {
  <div class="student-card">
    <h3>{{ student.name }}</h3>
    <p>Ball: {{ student.score }}</p>
  </div>
}

<!-- Qo'shimcha o'zgaruvchilar -->
@for (student of students; track student.id;
      let i = $index;
      let isFirst = $first;
      let isLast = $last;
      let isEven = $even;
      let isOdd = $odd;
      let count = $count) {

  <div [class.first]="isFirst" [class.last]="isLast">
    <p>{{ i + 1 }} / {{ count }}. {{ student.name }}</p>

    @if (isFirst) {
      <span class="badge">TOP 1</span>
    }

    @if (isEven) {
      <span class="even-row">Juft</span>
    }
  </div>
}

<!-- Bo'sh array uchun @empty -->
@for (item of history; track item) {
  <p>{{ item }}</p>
} @empty {
  <p class="empty-state">Hali hisoblashlar yo'q</p>
}

```

**@for ning afzalliklari:**

* Soddaroq sintaksis
* `track` majburiy bo'lgani uchun performans yaxshi
* `@empty` bloki mavjud

#### 3.3 @switch - Yangi tanlov

**Eski usul:**

```html
<div [ngSwitch]="value">
  <p *ngSwitchCase="'a'">A</p>
  <p *ngSwitchCase="'b'">B</p>
  <p *ngSwitchDefault>Default</p>
</div>
```

**Yangi usul:**

```html
@switch (value) {
  @case ('a') {
    <p>A</p>
  }
  @case ('b') {
    <p>B</p>
  }
  @default {
    <p>Default</p>
  }
}
```

```tsx
export class CalculatorComponent {
  operation: string = 'add';
  difficulty: string = 'medium';
  status: 'pending' | 'success' | 'error' = 'pending';
}
```

```html
<!-- Operatsiya bo'yicha -->
@switch (operation) {
  @case ('add') {
    <div class="operation">
      <span class="icon">➕</span>
      <p>Qo'shish</p>
    </div>
  }
  @case ('subtract') {
    <div class="operation">
      <span class="icon">➖</span>
      <p>Ayirish</p>
    </div>
  }
  @case ('multiply') {
    <div class="operation">
      <span class="icon">✖️</span>
      <p>Ko'paytirish</p>
    </div>
  }
  @case ('divide') {
    <div class="operation">
      <span class="icon">➗</span>
      <p>Bo'lish</p>
    </div>
  }
  @default {
    <p>Operatsiya tanlanmagan</p>
  }
}

<!-- Qiyinlik darajasi -->
@switch (difficulty) {
  @case ('easy') {
    <span class="badge badge-success">⭐ Oson</span>
  }
  @case ('medium') {
    <span class="badge badge-warning">⭐⭐ O'rtacha</span>
  }
  @case ('hard') {
    <span class="badge badge-danger">⭐⭐⭐ Qiyin</span>
  }
}

<!-- Status bo'yicha -->
@switch (status) {
  @case ('pending') {
    <div class="alert alert-info">
      <span class="spinner"></span>
      Yuklanmoqda...
    </div>
  }
  @case ('success') {
    <div class="alert alert-success">
      ✓ Muvaffaqiyatli!
    </div>
  }
  @case ('error') {
    <div class="alert alert-danger">
      ✗ Xatolik yuz berdi
    </div>
  }
}

```

***

### Nazorat savollar

1. **Data Binding nima va necha xil turlari bor?**
2. **Interpolation va Property Binding o'rtasida qanday farq bor?**
3. **Two-way binding qanday ishlaydi va qaysi modul kerak?**
4. **`ngIf` va `@if` o'rtasida qanday farqlar bor?**
5. **`ngFor` da `trackBy` nima uchun muhim?🤔**
6. **Structural va Attribute directives farqi nimada?**
7. **`ngClass` va `ngStyle` qachon ishlatiladi?**
8. **Yangi `@for` sintaksisida `track` nima uchun majburiy? 🤔**
9. **`@empty` bloki qaysi holatlarda foydali?**
10. **`ngSwitch` va `@switch` sintaksisini taqqoslang**

### Test

[Quiz Bot](https://t.me/QuizBot?start=UKzdCl4M)

### Amaliy vazifalar

1. Quyidagini Angularda yasang (tugamlarni bossa input qiymati o’zgarishi kerak)<br>

   <figure><img src="/files/2ihxfiNfGPvpc44wnFBe" alt=""><figcaption></figcaption></figure>
2. **Kalkulyator**
   * Yuqoridagi bilimlarni o’zlashtirishga va takrorlashga harakat qiling.
   * O’tgan darsda berilgan calculatorni davom ettirib mustqali ravishda uni yangi bilimlar asosida qilishga harakat qiling.<br>

     <figure><img src="/files/PKeFsK5SKuHaEBeFFUIX" alt=""><figcaption></figcaption></figure>
3. **Talabalar ro'yxati NEW**

   **Talab:** Talabalar ro'yxatini boshqaradigan komponent.

   **Funksiyalar:**

   * Talaba qo'shish (ism, ball)
   * @for bilan ro'yxatni ko'rsatish
   * Ball bo'yicha rang:
     * 90+: yashil
     * 60-89: sariq
     * <60: qizil
   * O'chirish funksiyasi
   * @empty: "Talabalar yo'q"
4. **Todo List NEW (bu qo’shimcha ulgursangiz qilasiz)**

   **Talab:** Vazifalar ro'yxati yarating.

   **Funksiyalar:**

   * Vazifa qo'shish
   * Bajarilgan/bajarilmagan holat
   * ngClass: bajarilgan vazifani o'chirish
   * Filterlash: hammasi/bajarilgan/bajarilmagan
   * @switch bilan filter ko'rsatish


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/data-binding-va-direktivalar.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
