Pipes

אפשר לשנות את הדרך שבה מוצג המידע בדף ה-html.

Built-in Pipes

נגדיר משתנים לדוגמא:

ts file

public name = 'Dani';
public message = 'Welcome to the class';
public person = {
    firstName: 'John',
    lastName: 'Dou',
};
public date = new Date();

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

html file

Strings

<h2>{{ name | lowercase }}</h2>
<h2>{{ name | uppercase }}</h2>
<h2>{{ message | titlecase }}</h2>
<!-- Slicing with staring index -->
<h2>{{ name | slice:3 }}</h2>
<!-- Slicing with starting and ending index -->
<h2>{{ name | slice:3:5 }}</h2>
{{ person | json }}

Numbers

<!-- Give min numbers in the int and in the decimal place -->
{{ 5.678 | number: '1.2-3' }}
{{ 0.25 | percent }}
{{ 0.25 | currency }}
{{ 0.25 | currency: 'ILS' }}

Date

<h2>{{ date | date: 'short' }}</h2>
<h2>{{ date | date: 'shortDate' }}</h2>
<h2>{{ date | date: 'shortTime' }}</h2>

Custom Pipes

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

כדי ליצור את ה-pipe:

ng g p pipes/age

נקבל קובץ שבו אנחנו צריכים לממש את הפונקציה transform של ה-pipe.

ts file

@Pipe({
    name: 'age'
})

export class AgePipe implements PipeTransform{
    transform(value: any, args?: any): any {
        return null;
    }
}

נניח שאנחנו רוצים לקבל תאריך ולהציג את הגיל של המשתמש.

html file

{{ user.dob | age }}

ערך ה-value הוא הערך שנמצא לפני ה-pipe ועובר אלינו.

ts file

transform(value: any, args?: any): any {
    let currentYear: any = new Date().getFullYear();
    let userBirthYear: any = new Date(value).getFullYear();
    let userAge = currentYear - userBirthYear;

    return userAge;
}

ניווט במאמר

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

Services

טפסים

Routes

Directives

Http Client

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

Weekly Tutorial