Skip to content
Open
Show file tree
Hide file tree
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
24 changes: 10 additions & 14 deletions apps/signal/43-signal-input/src/app/user.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<string>();
readonly lastName = input<string>();
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<string>(() => `${this.name()} ${this.lastName() ?? ''}`);
category = computed<Category>(() => ageToCategory(this.age()));
}
26 changes: 19 additions & 7 deletions apps/signal/50-bug-in-effect/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
model,
signal,
} from '@angular/core';
import { FormsModule } from '@angular/forms';

Expand Down Expand Up @@ -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);
});
}
}
Loading