mirror of
https://github.com/Raghu-Ch/angular-challenges.git
synced 2026-02-10 12:53:03 -05:00
feat(challenge36): add solution on trackby
This commit is contained in:
@@ -24,7 +24,7 @@ If you would like to propose a challenge, this project is open source, so feel f
|
|||||||
|
|
||||||
## Challenges
|
## Challenges
|
||||||
|
|
||||||
Check [all 35 challenges](https://angular-challenges.vercel.app/)
|
Check [all 36 challenges](https://angular-challenges.vercel.app/)
|
||||||
|
|
||||||
## Contributors ✨
|
## Contributors ✨
|
||||||
|
|
||||||
|
|||||||
36
apps/performance/ngfor-optimize/.eslintrc.json
Normal file
36
apps/performance/ngfor-optimize/.eslintrc.json
Normal 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": {}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
13
apps/performance/ngfor-optimize/README.md
Normal file
13
apps/performance/ngfor-optimize/README.md
Normal 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/).
|
||||||
22
apps/performance/ngfor-optimize/jest.config.ts
Normal file
22
apps/performance/ngfor-optimize/jest.config.ts
Normal 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',
|
||||||
|
],
|
||||||
|
};
|
||||||
99
apps/performance/ngfor-optimize/project.json
Normal file
99
apps/performance/ngfor-optimize/project.json
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
58
apps/performance/ngfor-optimize/src/app/app.component.ts
Normal file
58
apps/performance/ngfor-optimize/src/app/app.component.ts
Normal 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 = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6
apps/performance/ngfor-optimize/src/app/app.config.ts
Normal file
6
apps/performance/ngfor-optimize/src/app/app.config.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { ApplicationConfig } from '@angular/core';
|
||||||
|
import { provideAnimations } from '@angular/platform-browser/animations';
|
||||||
|
|
||||||
|
export const appConfig: ApplicationConfig = {
|
||||||
|
providers: [provideAnimations()],
|
||||||
|
};
|
||||||
15
apps/performance/ngfor-optimize/src/app/generateList.ts
Normal file
15
apps/performance/ngfor-optimize/src/app/generateList.ts
Normal 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;
|
||||||
|
}
|
||||||
44
apps/performance/ngfor-optimize/src/app/list.service.ts
Normal file
44
apps/performance/ngfor-optimize/src/app/list.service.ts
Normal 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 })),
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -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>();
|
||||||
|
}
|
||||||
4
apps/performance/ngfor-optimize/src/app/person.model.ts
Normal file
4
apps/performance/ngfor-optimize/src/app/person.model.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export interface Person {
|
||||||
|
email: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
0
apps/performance/ngfor-optimize/src/assets/.gitkeep
Normal file
0
apps/performance/ngfor-optimize/src/assets/.gitkeep
Normal file
BIN
apps/performance/ngfor-optimize/src/favicon.ico
Normal file
BIN
apps/performance/ngfor-optimize/src/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
13
apps/performance/ngfor-optimize/src/index.html
Normal file
13
apps/performance/ngfor-optimize/src/index.html
Normal 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>
|
||||||
7
apps/performance/ngfor-optimize/src/main.ts
Normal file
7
apps/performance/ngfor-optimize/src/main.ts
Normal 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)
|
||||||
|
);
|
||||||
5
apps/performance/ngfor-optimize/src/styles.scss
Normal file
5
apps/performance/ngfor-optimize/src/styles.scss
Normal 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 */
|
||||||
2
apps/performance/ngfor-optimize/src/test-setup.ts
Normal file
2
apps/performance/ngfor-optimize/src/test-setup.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
import '@testing-library/jest-dom';
|
||||||
|
import 'jest-preset-angular/setup-jest';
|
||||||
14
apps/performance/ngfor-optimize/tailwind.config.js
Normal file
14
apps/performance/ngfor-optimize/tailwind.config.js
Normal 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: [],
|
||||||
|
};
|
||||||
10
apps/performance/ngfor-optimize/tsconfig.app.json
Normal file
10
apps/performance/ngfor-optimize/tsconfig.app.json
Normal 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"]
|
||||||
|
}
|
||||||
7
apps/performance/ngfor-optimize/tsconfig.editor.json
Normal file
7
apps/performance/ngfor-optimize/tsconfig.editor.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"include": ["src/**/*.ts"],
|
||||||
|
"compilerOptions": {
|
||||||
|
"types": ["jest", "node"]
|
||||||
|
}
|
||||||
|
}
|
||||||
32
apps/performance/ngfor-optimize/tsconfig.json
Normal file
32
apps/performance/ngfor-optimize/tsconfig.json
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
15
apps/performance/ngfor-optimize/tsconfig.spec.json
Normal file
15
apps/performance/ngfor-optimize/tsconfig.spec.json
Normal 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"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"total": 35,
|
"total": 36,
|
||||||
"🟢": 12,
|
"🟢": 13,
|
||||||
"🟠": 116,
|
"🟠": 116,
|
||||||
"🔴": 207
|
"🔴": 207
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -23,8 +23,8 @@ hero:
|
|||||||
import { Card, CardGrid } from '@astrojs/starlight/components';
|
import { Card, CardGrid } from '@astrojs/starlight/components';
|
||||||
|
|
||||||
<CardGrid>
|
<CardGrid>
|
||||||
<Card title="35 Challenges">
|
<Card title="36 Challenges">
|
||||||
This repository gathers 35 Challenges related to <b>Angular</b>, <b>Nx</b>, <b>RxJS</b>, <b>Ngrx</b> and <b>Typescript</b>.
|
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.
|
These challenges resolve around real-life issues or specific features to elevate your skills.
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Component } from '@angular/core';
|
|||||||
@Component({
|
@Component({
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [],
|
imports: [],
|
||||||
selector: 'lib-root',
|
selector: 'app-root',
|
||||||
template: ``,
|
template: ``,
|
||||||
styles: [''],
|
styles: [''],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ export async function challengeGenerator(tree: Tree, options: Schema) {
|
|||||||
tmpl: '',
|
tmpl: '',
|
||||||
projectName: names(options.name).name,
|
projectName: names(options.name).name,
|
||||||
title: options.title,
|
title: options.title,
|
||||||
challengeNumber,
|
challengeNumber: challengeNumber + 1,
|
||||||
docRepository: options.docRepository,
|
docRepository: options.docRepository,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { Tree, formatFiles } from '@nx/devkit';
|
import { Tree, formatFiles } from '@nx/devkit';
|
||||||
import { readFile, writeFile } from 'fs/promises';
|
|
||||||
|
|
||||||
const README_FILENAME = 'README.md';
|
const README_FILENAME = 'README.md';
|
||||||
const OMIT = ['memoized', 'projection', 'testing-table', 'testing-forms'];
|
const OMIT = ['memoized', 'projection', 'testing-table', 'testing-forms'];
|
||||||
@@ -46,10 +45,10 @@ function findHref(href) {
|
|||||||
|
|
||||||
async function rewriteFile(tree: Tree, file: string) {
|
async function rewriteFile(tree: Tree, file: string) {
|
||||||
console.log('Current file', file);
|
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 regex = new RegExp(/Answer:(\d+)/);
|
||||||
const match = buffer.match(regex);
|
const match = buffer.toString().match(regex);
|
||||||
|
|
||||||
if (!match) throw new Error('NO MATCH');
|
if (!match) throw new Error('NO MATCH');
|
||||||
|
|
||||||
@@ -69,19 +68,19 @@ async function rewriteFile(tree: Tree, file: string) {
|
|||||||
-2
|
-2
|
||||||
)}/${pathElts.at(-1)}/`;
|
)}/${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 regexTitle = new RegExp(/title:\s(🟢|🟠|🔴)\s(.+?)\n/);
|
||||||
const matchTitle = doc.match(regexTitle);
|
const matchTitle = doc.toString().match(regexTitle);
|
||||||
const title = matchTitle[2];
|
const title = matchTitle[2];
|
||||||
|
|
||||||
const regexCommand = new RegExp(/npx nx serve\s(.+?)`\s/);
|
const regexCommand = new RegExp(/npx nx serve\s(.+?)`\s/);
|
||||||
const matchCommand = buffer.match(regexCommand);
|
const matchCommand = buffer.toString().match(regexCommand);
|
||||||
|
|
||||||
let command = '';
|
let command = '';
|
||||||
if (!matchCommand) {
|
if (!matchCommand) {
|
||||||
const regexOldCommand = new RegExp(/nx serve\s(.+?)\*/);
|
const regexOldCommand = new RegExp(/nx serve\s(.+?)\*/);
|
||||||
command = buffer.match(regexOldCommand)[1];
|
command = buffer.toString().match(regexOldCommand)[1];
|
||||||
} else {
|
} else {
|
||||||
command = matchCommand[1];
|
command = matchCommand[1];
|
||||||
}
|
}
|
||||||
@@ -103,12 +102,12 @@ npx nx serve ${command}
|
|||||||
Challenge documentation is [here](${link}).
|
Challenge documentation is [here](${link}).
|
||||||
`;
|
`;
|
||||||
|
|
||||||
await writeFile(file, finalText, { encoding: 'utf-8' });
|
tree.write(file, finalText);
|
||||||
|
|
||||||
///**** */
|
///**** */
|
||||||
|
|
||||||
const regexHref = new RegExp(/<a href=("|')(.+?)("|')/, 'g');
|
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);
|
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 regexHeader = new RegExp(/([\s\S]*?)\s:::note/);
|
||||||
const header = doc.match(regexHeader)[1];
|
const header = doc.toString().match(regexHeader)[1];
|
||||||
|
|
||||||
console.log('header', header);
|
console.log('header', header);
|
||||||
|
|
||||||
const regexContent = new RegExp(
|
const regexContent = new RegExp(
|
||||||
/Author: Thomas Laforge([\s\S]*?)### Submitting your work/
|
/Author: Thomas Laforge([\s\S]*?)### Submitting your work/
|
||||||
);
|
);
|
||||||
const matchContent = buffer.match(regexContent);
|
const matchContent = buffer.toString().match(regexContent);
|
||||||
|
|
||||||
let content = '';
|
let content = '';
|
||||||
if (!matchContent) {
|
if (!matchContent) {
|
||||||
const regexOldContent = new RegExp(
|
const regexOldContent = new RegExp(
|
||||||
/Author: Thomas Laforge([\s\S]*?)## Submitting your work/
|
/Author: Thomas Laforge([\s\S]*?)## Submitting your work/
|
||||||
);
|
);
|
||||||
content = buffer.match(regexOldContent)[1];
|
content = buffer.toString().match(regexOldContent)[1];
|
||||||
} else {
|
} else {
|
||||||
content = matchContent[1];
|
content = matchContent[1];
|
||||||
}
|
}
|
||||||
@@ -184,7 +183,7 @@ ${content}
|
|||||||
${footerText}
|
${footerText}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
await writeFile(docFile, fullDocText, { encoding: 'utf-8' });
|
tree.write(docFile, fullDocText);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function readmeGenerator(tree: Tree) {
|
export async function readmeGenerator(tree: Tree) {
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
export * from './lib/cd-flashing.directive';
|
export * from './lib/cd-flashing.directive';
|
||||||
|
export { NgForTrackByModule } from './lib/track-by.directive';
|
||||||
|
|||||||
51
libs/shared/directives/src/lib/track-by.directive.ts
Normal file
51
libs/shared/directives/src/lib/track-by.directive.ts
Normal 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 {}
|
||||||
Reference in New Issue
Block a user