Angular 6: Creating a Custom Date Pipe in TypeScript

Additionally, you should include the import of the Angular common module in your app module and add it to your component’s providers list. One possible solution is to simplify by making a single API call and returning an object.


Solution:

The explanation for this can be found in the documentation.

Angular’s lack of pipes for filtering or sorting lists is not accidental. This omission is deliberate due to their poor performance and interference with aggressive minification. Therefore, the Angular team and experienced developers highly advise incorporating filtering and sorting logic directly into the component.

It is advisable to eliminate the use of a pipe and instead incorporate the logic directly within the component.

For example, one approach is to incorporate the logic within the feature itself.

export class TodoService {
  private todos: Todo[] = [];
  GetAll(): Todo[]{
    return this.todos;
  }
  GetUncompleted() {
    return this.todos.filter(td => !td.completed);
  }
  ...

Your problem stems from assigning the todos value only once, during the initial setup of your components.

When an item is added to the list of todos without updating the value, the change becomes invisible.

To address this issue, there are two possible solutions: the first option involves utilizing getters.

Getters, which are simple to use, are special functions that update their values when called. For example, in your

todo.component

, it would provide the following result:

get todos() { return this.todoService.getAll(); }

Now, it is possible to incorporate it into your template.

*ngFor="let todo of todos"

And this will be updated.

I have provided a stackblitz demonstration to illustrate the functionality of getters.

To address the issue of repetition, you can consider using RxJS as an alternative solution. RxJS is an event-based approach where an event is triggered whenever there is an update to your list. Although this option may be more challenging, I have created a stackblitz example to assist you in comprehending it.

Whenever your list is updated, your components receive an event notifying them to update the list of todos.

Frequently Asked Questions