feat(challenge36): add solution on trackby

This commit is contained in:
thomas
2023-10-02 21:42:47 +02:00
parent 0a5bc8514c
commit c062613a8e
30 changed files with 564 additions and 20 deletions

View File

@@ -24,7 +24,7 @@ If you would like to propose a challenge, this project is open source, so feel f
## Challenges
Check [all 35 challenges](https://angular-challenges.vercel.app/)
Check [all 36 challenges](https://angular-challenges.vercel.app/)
## Contributors ✨

View File

@@ -0,0 +1,36 @@
{
"extends": ["../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "app",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
}
]
},
"extends": [
"plugin:@nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
]
},
{
"files": ["*.html"],
"extends": ["plugin:@nx/angular-template"],
"rules": {}
}
]
}

View File

@@ -0,0 +1,13 @@
# NgFor Optimization
> Author: Thomas Laforge
### Run Application
```bash
npx nx serve performance-ngfor-optimize
```
### Documentation and Instruction
Challenge documentation is [here](https://angular-challenges.vercel.app/challenges/angular-performance/36-ngfor-optimize/).

View File

@@ -0,0 +1,22 @@
/* eslint-disable */
export default {
displayName: 'performance-ngfor-optimize',
preset: '../../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
coverageDirectory: '../../../coverage/apps/performance/ngfor-optimize',
transform: {
'^.+\\.(ts|mjs|js|html)$': [
'jest-preset-angular',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
],
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
};

View File

@@ -0,0 +1,99 @@
{
"name": "performance-ngfor-optimize",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"prefix": "app",
"sourceRoot": "apps/performance/ngfor-optimize/src",
"tags": [],
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/performance/ngfor-optimize",
"index": "apps/performance/ngfor-optimize/src/index.html",
"main": "apps/performance/ngfor-optimize/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "apps/performance/ngfor-optimize/tsconfig.app.json",
"assets": [
"apps/performance/ngfor-optimize/src/favicon.ico",
"apps/performance/ngfor-optimize/src/assets"
],
"styles": [
"apps/performance/ngfor-optimize/src/styles.scss",
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css"
],
"scripts": [],
"allowedCommonJsDependencies": ["seedrandom"]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"executor": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "performance-ngfor-optimize:build:production"
},
"development": {
"browserTarget": "performance-ngfor-optimize:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "performance-ngfor-optimize:build"
}
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"apps/performance/ngfor-optimize/**/*.ts",
"apps/performance/ngfor-optimize/**/*.html"
]
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "apps/performance/ngfor-optimize/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
}
}
}

View File

@@ -0,0 +1,58 @@
import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { PersonService } from './list.service';
import { PersonListComponent } from './person-list.component';
@Component({
standalone: true,
imports: [
PersonListComponent,
FormsModule,
MatFormFieldModule,
MatInputModule,
],
providers: [PersonService],
selector: 'app-root',
template: `
<h1 class="font-semibold text-center text-3xl" title="Title">
List of Persons
</h1>
<mat-form-field class="w-3/4">
<input
placeholder="Add one member to the list"
matInput
type="text"
[(ngModel)]="label"
(keydown)="handleKey($event)" />
</mat-form-field>
<app-person-list
class="max-w-2xl w-3/4"
[persons]="persons()"
(delete)="personService.deletePerson($event)"
(update)="personService.updatePerson($event)" />
`,
host: {
class: 'flex items-center flex-col gap-5',
},
})
export class AppComponent implements OnInit {
readonly personService = inject(PersonService);
readonly persons = this.personService.persons;
label = '';
ngOnInit(): void {
this.personService.loadPersons();
}
handleKey(event: any) {
if (event.keyCode === 13) {
this.personService.addPerson(this.label);
this.label = '';
}
}
}

View File

@@ -0,0 +1,6 @@
import { ApplicationConfig } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
export const appConfig: ApplicationConfig = {
providers: [provideAnimations()],
};

View File

@@ -0,0 +1,15 @@
import { randEmail, randFirstName } from '@ngneat/falso';
import { Person } from './person.model';
export function generateList() {
const arr: Person[] = [];
for (let i = 0; i < 50; i++) {
arr.push({
email: randEmail(),
name: randFirstName(),
});
}
return arr;
}

View File

@@ -0,0 +1,44 @@
import { Injectable, inject, signal } from '@angular/core';
import { randEmail, randFirstName } from '@ngneat/falso';
import { generateList } from './generateList';
import { Person } from './person.model';
@Injectable()
export class PersonService {
private readonly fakeBackend = inject(FakeBackendService);
readonly persons = signal<Person[]>([]);
loadPersons() {
this.persons.set(generateList());
}
deletePerson(email: string) {
this.persons.set(
this.fakeBackend
.returnNewList(this.persons())
.filter((p) => p.email !== email)
);
}
updatePerson(email: string) {
this.persons.set(
this.fakeBackend
.returnNewList(this.persons())
.map((p) => (p.email === email ? { email, name: randFirstName() } : p))
);
}
addPerson(name: string) {
this.persons.set([
{ email: randEmail(), name },
...this.fakeBackend.returnNewList(this.persons()),
]);
}
}
@Injectable({ providedIn: 'root' })
export class FakeBackendService {
returnNewList = (input: Person[]): Person[] => [
...input.map((i) => ({ ...i })),
];
}

View File

@@ -0,0 +1,37 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Person } from './person.model';
@Component({
selector: 'app-person-list',
standalone: true,
imports: [CommonModule],
template: `
<div
*ngFor="let person of persons"
class="flex justify-between items-center border-b">
<h3>{{ person.name }}</h3>
<div class="flex gap-10 py-1">
<button
class="border rounded-md p-2 bg-blue-500 text-white"
(click)="update.emit(person.email)">
UPDATE
</button>
<button
class="border rounded-md p-2 bg-red-500 text-white"
(click)="delete.emit(person.email)">
DELETE
</button>
</div>
</div>
`,
host: {
class: 'w-full flex flex-col',
},
})
export class PersonListComponent {
@Input() persons: Person[] = [];
@Output() delete = new EventEmitter<string>();
@Output() update = new EventEmitter<string>();
}

View File

@@ -0,0 +1,4 @@
export interface Person {
email: string;
name: string;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>performance-ngfor-optimize</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@@ -0,0 +1,7 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
);

View File

@@ -0,0 +1,5 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* You can add global styles to this file, and also import other style files */

View File

@@ -0,0 +1,2 @@
import '@testing-library/jest-dom';
import 'jest-preset-angular/setup-jest';

View File

@@ -0,0 +1,14 @@
const { createGlobPatternsForDependencies } = require('@nx/angular/tailwind');
const { join } = require('path');
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html}'),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
extend: {},
},
plugins: [],
};

View File

@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"types": []
},
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"],
"exclude": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts"]
}

View File

@@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"include": ["src/**/*.ts"],
"compilerOptions": {
"types": ["jest", "node"]
}
}

View File

@@ -0,0 +1,32 @@
{
"compilerOptions": {
"target": "es2022",
"useDefineForClassFields": false,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
},
{
"path": "./tsconfig.editor.json"
}
],
"extends": "../../../tsconfig.base.json",
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@@ -0,0 +1,15 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node", "@testing-library/jest-dom"]
},
"files": ["src/test-setup.ts"],
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}

View File

@@ -1,6 +1,6 @@
{
"total": 35,
"🟢": 12,
"total": 36,
"🟢": 13,
"🟠": 116,
"🔴": 207
}

View File

@@ -0,0 +1,54 @@
---
title: 🟢 NgFor Optimization
description: Challenge 36 is about ...
sidebar:
order: 13
badge: New
---
<div class="chip">Challenge #36</div>
## Information
In this application, we have a list of individuals that we can add, delete or update. If you open the developer Chrome panel by pressing **F12**, go to he <b>source</b> tab, and expand the element to see the list, you will notice that each time, you add, delete or update a list item, the entire DOM elements are destroyed and initialized again. (See video below).
<video controls src="https://github.com/tomalaforge/angular-challenges/assets/30832608/71b90307-3ee3-42c0-a532-b67ce4f20bf6">
</video>
We can also use the <b>Angular DevTool</b> to profile our application and understand what is happening inside our application. I will show you how to do it inside the following video.
<video controls src="https://github.com/tomalaforge/angular-challenges/assets/30832608/dd8108c6-1d89-4b05-9aa5-e760bd6f7f11">
</video>
:::note
If you don't know how to use it, read [the performance introduction page](/challenges/angular-performance/) first and come back after.
:::
If you need more information about `NgFor`, I invite you to read the [documentation](https://angular.io/api/common/NgFor) first.
## Statement
The goal of this challenge is to understand what is causing this DOM refresh and to solve it.
---
:::note
Start the project by running: `npx nx serve ngfor-optimize`.
:::
:::tip[Reminder]
Your PR title must start with <b>Answer:36</b>.
:::
<div class="article-footer">
<a
href="https://github.com/tomalaforge/angular-challenges/pulls?q=label%3A36+label%3Aanswer"
alt="NgFor Optimization community solutions">
❖ Community Answers
</a>
<a
href='https://github.com/tomalaforge/angular-challenges/pulls?q=label%3A36+label%3A"answer+author"'
alt="NgFor Optimization solution author">
▶︎ Author Answer
</a>
</div>

View File

@@ -23,8 +23,8 @@ hero:
import { Card, CardGrid } from '@astrojs/starlight/components';
<CardGrid>
<Card title="35 Challenges">
This repository gathers 35 Challenges related to <b>Angular</b>, <b>Nx</b>, <b>RxJS</b>, <b>Ngrx</b> and <b>Typescript</b>.
<Card title="36 Challenges">
This repository gathers 36 Challenges related to <b>Angular</b>, <b>Nx</b>, <b>RxJS</b>, <b>Ngrx</b> and <b>Typescript</b>.
These challenges resolve around real-life issues or specific features to elevate your skills.
</Card>

View File

@@ -3,7 +3,7 @@ import { Component } from '@angular/core';
@Component({
standalone: true,
imports: [],
selector: 'lib-root',
selector: 'app-root',
template: ``,
styles: [''],
})

View File

@@ -51,7 +51,7 @@ export async function challengeGenerator(tree: Tree, options: Schema) {
tmpl: '',
projectName: names(options.name).name,
title: options.title,
challengeNumber,
challengeNumber: challengeNumber + 1,
docRepository: options.docRepository,
});

View File

@@ -1,5 +1,4 @@
import { Tree, formatFiles } from '@nx/devkit';
import { readFile, writeFile } from 'fs/promises';
const README_FILENAME = 'README.md';
const OMIT = ['memoized', 'projection', 'testing-table', 'testing-forms'];
@@ -46,10 +45,10 @@ function findHref(href) {
async function rewriteFile(tree: Tree, file: string) {
console.log('Current file', file);
const buffer = await readFile(file, { encoding: 'utf-8' });
const buffer = tree.read(file);
const regex = new RegExp(/Answer:(\d+)/);
const match = buffer.match(regex);
const match = buffer.toString().match(regex);
if (!match) throw new Error('NO MATCH');
@@ -69,19 +68,19 @@ async function rewriteFile(tree: Tree, file: string) {
-2
)}/${pathElts.at(-1)}/`;
const doc = await readFile(docFile, { encoding: 'utf-8' });
const doc = tree.read(docFile);
const regexTitle = new RegExp(/title:\s(🟢|🟠|🔴)\s(.+?)\n/);
const matchTitle = doc.match(regexTitle);
const matchTitle = doc.toString().match(regexTitle);
const title = matchTitle[2];
const regexCommand = new RegExp(/npx nx serve\s(.+?)`\s/);
const matchCommand = buffer.match(regexCommand);
const matchCommand = buffer.toString().match(regexCommand);
let command = '';
if (!matchCommand) {
const regexOldCommand = new RegExp(/nx serve\s(.+?)\*/);
command = buffer.match(regexOldCommand)[1];
command = buffer.toString().match(regexOldCommand)[1];
} else {
command = matchCommand[1];
}
@@ -103,12 +102,12 @@ npx nx serve ${command}
Challenge documentation is [here](${link}).
`;
await writeFile(file, finalText, { encoding: 'utf-8' });
tree.write(file, finalText);
///**** */
const regexHref = new RegExp(/<a href=("|')(.+?)("|')/, 'g');
const href = buffer.match(regexHref).map(findHref);
const href = buffer.toString().match(regexHref).map(findHref);
console.log('HREF', href);
@@ -150,21 +149,21 @@ Your PR title must start with <b>Answer:${number}</b>.
}
const regexHeader = new RegExp(/([\s\S]*?)\s:::note/);
const header = doc.match(regexHeader)[1];
const header = doc.toString().match(regexHeader)[1];
console.log('header', header);
const regexContent = new RegExp(
/Author: Thomas Laforge([\s\S]*?)### Submitting your work/
);
const matchContent = buffer.match(regexContent);
const matchContent = buffer.toString().match(regexContent);
let content = '';
if (!matchContent) {
const regexOldContent = new RegExp(
/Author: Thomas Laforge([\s\S]*?)## Submitting your work/
);
content = buffer.match(regexOldContent)[1];
content = buffer.toString().match(regexOldContent)[1];
} else {
content = matchContent[1];
}
@@ -184,7 +183,7 @@ ${content}
${footerText}
`;
await writeFile(docFile, fullDocText, { encoding: 'utf-8' });
tree.write(docFile, fullDocText);
}
export async function readmeGenerator(tree: Tree) {

View File

@@ -1 +1,2 @@
export * from './lib/cd-flashing.directive';
export { NgForTrackByModule } from './lib/track-by.directive';

View File

@@ -0,0 +1,51 @@
/* eslint-disable @angular-eslint/directive-selector */
import { NgFor, NgForOf } from '@angular/common';
import {
Directive,
Input,
NgIterable,
NgModule,
Provider,
inject,
} from '@angular/core';
@Directive({
selector: '[ngForTrackByProp]',
standalone: true,
})
export class NgForTrackByPropDirective<T> {
@Input() ngForOf!: NgIterable<T>;
@Input()
set ngForTrackByProp(ngForTrackBy: keyof T) {
// setter
this.ngFor.ngForTrackBy = (index: number, item: T) => item[ngForTrackBy];
}
private ngFor = inject(NgForOf<T>, { self: true });
}
@Directive({
selector: '[ngForTrackById]',
standalone: true,
})
export class NgForTrackByIdDirective<T extends { id: string | number }> {
@Input() ngForOf!: NgIterable<T>; // 2
private ngFor = inject(NgForOf<T>, { self: true }); // 3
constructor() {
this.ngFor.ngForTrackBy = (index: number, item: T) => item.id; // 4
}
}
export const NgForTrackByDirective: Provider[] = [
NgForTrackByIdDirective,
NgForTrackByPropDirective,
];
@NgModule({
imports: [NgFor, NgForTrackByDirective],
exports: [NgFor, NgForTrackByDirective],
})
export class NgForTrackByModule {}