Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 21 additions & 17 deletions content/components/minimize-logic-in-templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,42 @@ When we put too much logic in our templates, we are making our applications more

In addition, too much logic inside the template makes them less readable. We cannot take a quick glance at the template and quickly understand what's going on.

# Solution

Try to avoid putting too much logic in your templates.

For example here, we have have an `*ngIf` that has too much logic.
For example here, we have have an `@if` that has too much logic.

```ts
@Component({
template: `<div *ngIf="users && users.length > 1 && visible">content to show</div>`,
template: `
@if(users().length && !users().some(user => user.criteriaMet)) {
<p>No items meet the criteria.</p>
}
`,
})
export class SomeComponent {
users: User[];
visible: boolean;
users: signal<User[]>([]);
}
```

We can refactor this by extracting the logic into the component's class. This will make the template more readable and the logic easier to test.
# Solution

Let's refactor this by extracting the logic into the component's class. This will make the template more readable and the logic easier to test.
To do so, we use `computed`, introduced in Angular 16, to create a computed property that will be used in the template.

```ts
@Component({
template: `<div *ngIf="usersExistsAndVisible()">content to show</div>`,
template: `
@if(noCriteriaMet()) {
<p>No items meet the criteria.</p>
}
`,
})
export class SomeComponent {
users: User[];
visible: boolean;

usersExistsAndVisible() {
return this.users && this.users.length > 1 && this.visible;
}
users: signal<User[]>([]);

noCriteriaMet = computed(() => this.users().length && !this.users().some(user => user.criteriaMet));
}
```

### Best Practices

Be careful when the `ChangeDetectionStrategy` is set to `Default`, as it'd cause the functions bound in the template to be called each time the `Change Detection Cycle` runs. You can optimize this by turning on the `OnPush` change detection strategy and leverage the `async` pipe in combination with `Observables` that return the desired value.
Be careful when the `ChangeDetectionStrategy` is set to `Default`, as it'd cause the functions bound in the template to be called each time the `Change Detection Cycle` runs.
You can optimize this by turning on the `OnPush` change detection strategy and leverage the `async` pipe in combination with `Observables` that return the desired value.