שינוי רצף התצוגה – Directives

תנאים ולולאות משפיעים על הדרך שבה אנחנו רואים את התוכן בתבנית.

על מנת להשפיע על מבנה הדף נשתמש ב-directives.

ngIf

מציגים את האלמנט רק אם התנאי נכון.

component html file

<h2 *ngIf="true">Some heading</h2>

אפשר להשתמש בערכים של משתנים על מנת להעריך את התנאי:

<h2 *ngIf="propName">Some heading</h2>

אפשר להשתמש באפשרות של else כדי לתת תבנית אלטרנטיבית במקרה שהתנאי לא מתקיים:

<h2 *ngIf="displayName; else elseBlock">Some heading</h2>
<ng-template #elseBlock>
  <h2>Alternative heading</h2>
</ng-template>

אפשר להשתמש בטמפלטים לכל מצב של התנאי:

<div *ngIf="displayName; then thenBlock; else elseBlock"></div>
<ng-template #thenBlock>
  <h2>First heading</h2>
</ng-template>
<ng-template #elseBlock>
  <h2>Alternative heading</h2>
</ng-template>

ngSwitch

שימוש בסדרה של תנאים

component html file

<div [ngSwitch]="color">
  <div *ngSwitchCase="'red'">Picked red</div>
  <div *ngSwitchCase="'green'">Picked green</div>
  ...
  <div *ngSwitchDefault>Pick again</div>
</div>

component ts file

public color = 'red';

ngFor

יצירת רשימה של אלמנטים

component ts file

public colors = ['red', 'green', 'blue'];

component html file

<div *ngFor="let color of colors">
  <h2>{{ color }}</h2>
</div>

יש משתנים נוספים שאפשר להשתמש בהם בתוך לולאת ה-for:

<div *ngFor="let color of colors; index as i"> ... </div>
<div *ngFor="let color of colors; first as f">first return true if the element is the first</div>
<div *ngFor="let color of colors; last as l"> ... </div>
<div *ngFor="let color of colors; odd as o"> ... </div>
<div *ngFor="let color of colors; even as e"> ... </div>

Template reference variable

אפשר ליצור משתנה שיחזיק בתוכו אלמנט html

component html file

<input type="text" #myVariable>

שם המשתנה myVariable מחזיק את האלמנט ב-DOM. אם רוצים להשתמש בערך של המשתנה, אפשר להתייחס אליו במסמך.

<p>{{ myVariable.value }}</p>

בעיה לפעמים העמוד עולה לפני שיש ערך בתוך המשתנה, ואז אנחנו צריכים להגיד ל-DOM שהיה שינוי במשתנה. אפשר להשתמש באירוע keyup כדי לעשות את זה.

<input type="text" #myVariable (keyup)="0"/>

את המשתנה שנוצר אפשר לקרוא ב-class.

component html file

<input type="text" #myVariable>
<button (click)="sayHello(myVariable)"></button>

component ts file

sayHello(inputEl: HTMLInputElement) {
    console.log('Hello ' + inputEl.value);
}

ניווט במאמר

קומפוננטות - Components

Services

טפסים

Routes

Directives

Http Client

מאמרים אחרונים

Weekly Tutorial