diff --git a/apps/signal/43-signal-input/src/app/user.component.ts b/apps/signal/43-signal-input/src/app/user.component.ts index 553042ebb..5fd3a3c66 100644 --- a/apps/signal/43-signal-input/src/app/user.component.ts +++ b/apps/signal/43-signal-input/src/app/user.component.ts @@ -2,8 +2,9 @@ import { TitleCasePipe } from '@angular/common'; import { ChangeDetectionStrategy, Component, - Input, - OnChanges, + computed, + input, + numberAttribute, } from '@angular/core'; type Category = 'Youth' | 'Junior' | 'Open' | 'Senior'; @@ -18,23 +19,18 @@ const ageToCategory = (age: number): Category => { selector: 'app-user', imports: [TitleCasePipe], template: ` - {{ fullName | titlecase }} plays tennis in the {{ category }} category!! + {{ fullName() | titlecase }} plays tennis in the {{ category() }} category!! `, host: { class: 'text-xl text-green-800', }, changeDetection: ChangeDetectionStrategy.OnPush, }) -export class UserComponent implements OnChanges { - @Input({ required: true }) name!: string; - @Input() lastName?: string; - @Input() age?: string; +export class UserComponent { + readonly name = input.required(); + readonly lastName = input(); + readonly age = input(0, { transform: numberAttribute }); - fullName = ''; - category: Category = 'Junior'; - - ngOnChanges(): void { - this.fullName = `${this.name} ${this.lastName ?? ''}`; - this.category = ageToCategory(Number(this.age)); - } + fullName = computed(() => `${this.name()} ${this.lastName() ?? ''}`); + category = computed(() => ageToCategory(this.age())); } diff --git a/apps/signal/50-bug-in-effect/src/app/app.component.ts b/apps/signal/50-bug-in-effect/src/app/app.component.ts index ec6ba09b0..f67f582e0 100644 --- a/apps/signal/50-bug-in-effect/src/app/app.component.ts +++ b/apps/signal/50-bug-in-effect/src/app/app.component.ts @@ -1,8 +1,10 @@ import { ChangeDetectionStrategy, Component, + computed, effect, model, + signal, } from '@angular/core'; import { FormsModule } from '@angular/forms'; @@ -35,18 +37,28 @@ import { FormsModule } from '@angular/forms'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class AppComponent { - drive = model(false); - ram = model(false); - gpu = model(false); + protected readonly drive = model(false); + protected readonly ram = model(false); + protected readonly gpu = model(false); + + private readonly currentNoSelected = signal(0); + + private readonly noOfModelsSelected = computed( + () => + [this.drive(), this.ram(), this.gpu()].filter((model) => model).length, + ); + + private prev = this.currentNoSelected(); constructor() { - /* - Explain for your junior team mate why this bug occurs ... - */ effect(() => { - if (this.drive() || this.ram() || this.gpu()) { + const valueNow = this.noOfModelsSelected(); + const shouldFireAlert = valueNow > this.prev; + if (shouldFireAlert) { alert('Price increased!'); } + this.prev = valueNow; + this.currentNoSelected.set(valueNow); }); } }