Skip to content

Commit 2fdafd3

Browse files
authored
[2024-11-01] Czy wiesz, że w Angular 17 została wprowadzona alternatywa dla *ngIf? (#258)
1 parent 7142a6a commit 2fdafd3

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
---
2+
layout: post
3+
title: Czy wiesz, że w Angular 17 została wprowadzona alternatywa dla *ngIf?
4+
description: ""
5+
date: 2024-11-01T08:00:00+01:00
6+
published: true
7+
didyouknow: true
8+
lang: pl
9+
author: dmejer
10+
image: /assets/img/posts/2024-11-04-czy-wiesz-ze-od-angular-17-mozna-uzywac-if-zamiast-ngif/thumbnail.webp
11+
tags:
12+
- javascript
13+
---
14+
W Angular 17 pojawiło się *built-it control flow*, które zostało ustabilizowane w wersji 18. Są to zamienniki dyrektyw `*ngIf`, `*ngFor`, `*ngSwitch`.
15+
16+
`@if` jest odpowiednikiem `*ngIf`. Przykładowe wykorzystanie:
17+
```
18+
// *ngIf - if-else
19+
<div *ngIf="a > b; then aGreaterBlock else aLessOrEqualBlock"></div>
20+
<ng-template #aGreaterBlock>A jest większe niż B</ng-template>
21+
<ng-template #aLessOrEqualBlock>A jest mniejsze lub równe B</ng-template>
22+
23+
// @if - if, else if, else
24+
@if (a > b) {
25+
A jest większe niż B
26+
} @else if (a < b){
27+
A jest mniejsze niż B
28+
} @else {
29+
A jest równe B
30+
}
31+
```
32+
33+
`@if` można używać również z `async pipe`. Przykład wykorzystania:
34+
```
35+
// *ngIf - async pipe
36+
<ng-container *ngIf="vm$ | async as viewModel">
37+
{{ viewModel.attachemnts.length }}
38+
</ng-container>
39+
40+
// @if - async pipe
41+
@if (vm$ | async; as viewModel) {
42+
{{ viewModel.attachemnts.length }}
43+
}
44+
```
45+
46+
`@if` poprawia czytelność szablonów, oddziela logikę od tagów html oraz oferuje klauzulę `@else`, która będzie wykonana, jeśli zdefiniowany warunek nie zostanie spełniony.
47+
48+
## Dokumentacja
49+
- [https://angular.dev/guide/templates/control-flow](https://angular.dev/guide/templates/control-flow)
50+
- [https://angular.dev/api/common/NgIf](https://angular.dev/api/common/NgIf)
10.5 KB
Loading

0 commit comments

Comments
 (0)