|
| 1 | +import { CommonModule } from '@angular/common'; |
| 2 | +import { Component, computed, effect, inject } from '@angular/core'; |
| 3 | +import { FormsModule } from '@angular/forms'; |
| 4 | +import { MatIcon } from '@angular/material/icon'; |
| 5 | +import { MatInputModule } from '@angular/material/input'; |
| 6 | +import { MatListModule } from '@angular/material/list'; |
| 7 | +import { MatTableDataSource, MatTableModule } from '@angular/material/table'; |
| 8 | +import { TodoEntityResourceStore } from './todo-entity-resource.store'; |
| 9 | + |
| 10 | +@Component({ |
| 11 | + selector: 'demo-todo-entity-resource', |
| 12 | + standalone: true, |
| 13 | + imports: [ |
| 14 | + CommonModule, |
| 15 | + FormsModule, |
| 16 | + MatIcon, |
| 17 | + MatInputModule, |
| 18 | + MatListModule, |
| 19 | + MatTableModule, |
| 20 | + ], |
| 21 | + templateUrl: './todo-entity-resource.component.html', |
| 22 | + styles: [], |
| 23 | +}) |
| 24 | +export class TodoEntityResourceComponent { |
| 25 | + protected readonly store = inject(TodoEntityResourceStore); |
| 26 | + protected newTitle = ''; |
| 27 | + protected readonly dataSource = new MatTableDataSource<{ |
| 28 | + id: number; |
| 29 | + title: string; |
| 30 | + completed: boolean; |
| 31 | + }>([]); |
| 32 | + protected readonly filtered = computed(() => |
| 33 | + this.store.entities().filter((t) => |
| 34 | + (this.store.filter() || '') |
| 35 | + .toLowerCase() |
| 36 | + .split(/\s+/) |
| 37 | + .filter((s) => s.length > 0) |
| 38 | + .every((s) => t.title.toLowerCase().includes(s)), |
| 39 | + ), |
| 40 | + ); |
| 41 | + constructor() { |
| 42 | + effect(() => { |
| 43 | + this.dataSource.data = this.filtered(); |
| 44 | + }); |
| 45 | + } |
| 46 | + trackById = (_: number, t: { id: number }) => t.id; |
| 47 | + add() { |
| 48 | + const title = this.newTitle.trim(); |
| 49 | + if (!title) return; |
| 50 | + const ids = this.store.ids() as Array<number>; |
| 51 | + const nextId = ids.length ? Math.max(...ids) + 1 : 1; |
| 52 | + this.store.addTodo({ id: nextId, title, completed: false }); |
| 53 | + this.newTitle = ''; |
| 54 | + } |
| 55 | +} |
0 commit comments