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

@@ -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"
]
}