So, I have parent component :
@Component({
selector: 'app-root',
template: `
<app-header
(filterItems)="filterItems($event)"
[length]="items.length"
></app-header>
`,
})
export class AppComponent implements OnInit {
items: ItemT[] = [];
constructor(private mainService: MainService) {}
filterItems(filter: string) {
this.items = this.mainService.filterItems(filter);
}
async ngOnInit() {
this.items = await this.mainService.getItems();
}
}
Then header:
@Component({
selector: 'app-header',
template: `
<app-filtration (filterItems)="filterItems.emit($event)"></app-filtration>
<h2>
<span>{{ length }}</span>
<ng-template #one>item</ng-template>
<ng-template #many>items</ng-template>
<ng-container *ngIf="length === 1; then one; else many"></ng-container>
</h2>`,
})
export class HeaderComponent {
@Input() length!: number;
@Output() filterItems = new EventEmitter<string>();
}
Filtration-component:
@Component({
selector: 'app-filtration',
template: `
<div>insert a filter here</div>
<input
class="input filter-input"
[(ngModel)]="filter"
(input)="filterItems.emit(filter)"
/>
<button (click)="clear()"></button>
`,
})
export class FiltrationComponent {
constructor(private mainService: MainService) {}
filter: 'all' | 'active' | 'done' = 'all';
@Output() filterItems = new EventEmitter<string>();
clear() {
this.mainService.items = [];
}
}
And finally, I have a service:
const ITEMS_API = 'http://localhost:3000/base';
export class MainService {
items: ItemT[] = [];
constructor(private http: HttpClient) {}
async getItems() {
const json = await fetch(ITEMS_API);
this.items = await json.json();
return this.items;
}
filterItems(filter: string) {
if (filter === 'all') {
return this.items;
}
return this.items.filter((item) => {
return filter === 'done' ? item.done : !item.done;
});
}
}
So, I can emit events from child components to parent and by this way parent component props changes, and component re-renders. But I've to send listeners up the tree from every child to a parent.
Is there another way to do this? I was trying to do this in FiltrationComponent in "clear" function by clearing prop in the service, but it doesn't work.
Could you help, please 🦔