### Install locally built Angular CLI packages into an example project Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md Run in the example project repository to install the tarballs generated by the local build. The example project will then use the locally built tooling. ```shell cd "${EXAMPLE_ANGULAR_PROJECT_REPO}" npm install -D ${CLI_REPO}/dist/*.tgz ``` -------------------------------- ### Install library and typings with npm Source: https://github.com/angular/angular-cli/wiki/stories-third-party-lib Install a library and its type definitions using npm. The first command installs the library as a runtime dependency, and the second installs its typings as a development dependency. ```bash npm install d3 --save npm install @types/d3 --save-dev ``` -------------------------------- ### Install classlist.js and web-animations-js Source: https://github.com/angular/angular-cli/blob/main/CHANGELOG.md Run this command to install the packages after adding the imports to the polyfills file. ```sh npm install classlist.js web-animations-js --save ``` -------------------------------- ### Global install of Angular CLI Source: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/completion/long-description.md Install the Angular CLI globally so the terminal can find the `ng` command. Use this if you get `command not found: ng` when setting up autocompletion. ```bash npm install -g @angular/cli ``` -------------------------------- ### Basic JSON Schema for hello world schematic Source: https://github.com/angular/angular-cli/blob/main/docs/specifications/schematic-prompts.md Initial schema with `name` and `useColor` properties before adding prompts. Used as the starting point for the prompt examples. ```json { "properties": { "name": { "type": "string", "minLength": 1, "default": "world" }, "useColor": { "type": "boolean" } } } ``` -------------------------------- ### Install dependencies and typings Source: https://github.com/angular/angular-cli/wiki/Upgrading-from-Beta.10-to-Beta.12 Install project dependencies and their corresponding TypeScript definitions. ```bash npm install --save ${LIBRARY} ``` ```bash npm install --save-dev @types/${LIBRARY} ``` -------------------------------- ### Install Flex Layout Nightly Build Source: https://github.com/angular/angular-cli/wiki/stories-include-angular-flex Use this command to install the nightly build version of the library. ```bash npm i --save @angular/flex-layout-builds ``` -------------------------------- ### Install jquery via ng install Source: https://github.com/angular/angular-cli/blob/main/docs/design/third-party-libraries.md Initializes a new project and installs the jquery library, making it available in the index. ```sh $ ng new my-app && cd my-app/ $ ng install jquery ``` -------------------------------- ### Install WSL from Powershell Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md Run this command in Powershell as administrator to install Windows Subsystem for Linux. ```bash wsl --install ``` -------------------------------- ### Start server command Source: https://github.com/angular/angular-cli/wiki/stories-universal-rendering Command to execute the bundled server file. ```bash node dist/server.js ``` -------------------------------- ### Path example: keyA.keyB.arrayC[3].value Source: https://github.com/angular/angular-cli/blob/main/docs/design/ngConfig.md Shows the JSON path format used by the `get` and `set` commands. Each dot separates a map key, and square brackets indicate an array index. ```text keyA.keyB.arrayC[3].value ``` -------------------------------- ### Install Flex Layout via npm Source: https://github.com/angular/angular-cli/wiki/stories-include-angular-flex Use this command to install the library and add it as a dependency to your package.json file. ```bash npm install --save @angular/flex-layout ``` -------------------------------- ### Production build and serve command Source: https://github.com/angular/angular-cli/wiki/stories-universal-rendering Command to build the application for production and start the server. ```bash npm run build:ssr && npm run serve:ssr ``` -------------------------------- ### Run the Angular application Source: https://github.com/angular/angular-cli/blob/main/README.md Navigates into the project directory and starts the local development server. ```bash cd [PROJECT NAME] ng serve ``` -------------------------------- ### Install library typings Source: https://github.com/angular/angular-cli/wiki/Upgrading-from-Beta.10-to-Beta.14 Install TypeScript typings for libraries that require them. ```bash npm install --save-dev @types/${LIBRARY} ``` -------------------------------- ### Install angularfire2 with command line arguments Source: https://github.com/angular/angular-cli/blob/main/docs/design/third-party-libraries.md Installs angularfire2 while providing the database URL via the --dbUrl flag to skip prompts. ```sh $ ng install angularfire2 --dbUrl=my-firebase-db.example.com ``` -------------------------------- ### Publish Angular CLI release with pnpm ng-dev release publish Source: https://github.com/angular/angular-cli/blob/main/docs/process/release.md Run this command to start the release process. It will guide you through prompts. Releases should be done in reverse semver order: Oldest LTS -> Newest LTS -> Patch -> RC -> Next. ```sh pnpm ng-dev release publish ``` -------------------------------- ### Install Bootstrap with npm Source: https://github.com/angular/angular-cli/wiki/stories-include-bootstrap Installs Bootstrap as a dependency and saves it to package.json using the --save option. ```sh npm install bootstrap --save ``` -------------------------------- ### Update package.json start script Source: https://github.com/angular/angular-cli/wiki/stories-using-corporate-proxy Edit the package.json start script to use the proxy.conf.js file with the --proxy-config flag. ```json "start": "ng serve --proxy-config proxy.conf.js", ``` -------------------------------- ### Install specific Angular CLI versions Source: https://github.com/angular/angular-cli/wiki/Home Commands to install a previous version, a pre-release, or a snapshot build from CI. The globally installed package delegates to the local one. ```bash npm install @angular/cli@6.0.2 ``` ```bash npm install @angular/cli@next ``` ```bash npm install @angular/cli@github:angular/cli-builds ``` ```bash npm install @angular/cli@github:angular/cli-builds#0123456789abcdef ``` -------------------------------- ### Start the web server with lite-server --baseDir="dist" Source: https://github.com/angular/angular-cli/wiki/stories-disk-serve Run this command in the second terminal to serve the `dist` folder. The default browser will open to the appropriate URL. ```bash lite-server --baseDir="dist" ``` -------------------------------- ### Install Angular CLI globally Source: https://github.com/angular/angular-cli/wiki/Home Installs the Angular CLI globally using npm. If an error occurs, it is likely a local npm setup issue, not a problem with Angular CLI. ```bash npm install -g @angular/cli ``` -------------------------------- ### Install Font Awesome dependency Source: https://github.com/angular/angular-cli/wiki/stories-include-font-awesome Command to install the font-awesome library and save it to package.json. ```bash npm install --save font-awesome ``` -------------------------------- ### Install angularfire2 with interactive prompt Source: https://github.com/angular/angular-cli/blob/main/docs/design/third-party-libraries.md Installs angularfire2 and prompts the user for the Firebase database URL. ```sh $ ng install angularfire2 > Please specify your Firebase database URL [my-app.firebaseio.com]: _ ``` -------------------------------- ### Install Angular Universal Dependencies Source: https://github.com/angular/angular-cli/wiki/stories-universal-rendering Install the necessary platform-server packages, loader utilities, and server runtime dependencies using npm. ```bash $ npm install --save @angular/platform-server @nguniversal/module-map-ngfactory-loader express $ npm install --save-dev ts-loader webpack-cli ``` -------------------------------- ### Configure non-global providers with ng CLI Source: https://github.com/angular/angular-cli/blob/main/docs/design/third-party-libraries.md Example workflow for creating a new app, generating a component, and installing a dependency without global providers using the --no-global-providers flag. ```bash ng new my-todo-app ng generate component database ng install --no-global-providers angularfirebase2 ng providers database angularfirebase2 ``` -------------------------------- ### Create new Angular project (CSS) Source: https://github.com/angular/angular-cli/wiki/stories-include-bootstrap Commands to create a new Angular project and navigate into it for the CSS setup. ```bash ng new my-app cd my-app ``` -------------------------------- ### Schedule jobs by name using a registry Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/architecture.md This example shows how to compose jobs by scheduling them based on their name from other jobs, including registering them in a SimpleJobRegistry and executing them via a SimpleScheduler. ```javascript // Runs a job on the hour, every hour, regardless of how long the job takes. // This creates a high order job by getting a job name and an argument, and scheduling the job // every hour. function scheduleJobOnTheHour(job, context) { const { name, argument } = job; // Destructure our input. return new Observable((observer) => { let timeout = 0; function _timeoutToNextHour() { // Just wait until the next hour. const t = new Date(); const secondsToNextHour = 3600 - t.getSeconds() - t.getMinutes() * 60; timeout = setTimeout(_scheduleJobAndWaitAnHour, secondsToNextHour); } function _scheduleJobAndWaitAnHour() { const subJob = context.scheduler.schedule(name, argument); // We do not forward the input to the sub-job but that would be a valid example as well. subJob.outboundBus.subscribe( (message) => observer.next(message), (error) => observer.error(error), // Do not forward completion, but use it to schedule the next job run. () => { _timeoutToNextHour(); }, ); } // Kick off by waiting for next hour. _timeoutToNextHour(); return () => clearTimeout(timeout); }); } const registry = new SimpleJobRegistry(); registry.register('schedule-job-on-the-hour', scheduleJobOnTheHour, { argument: { properties: { name: { type: 'string' }, argument: { type: true }, }, }, }); // Implementation left to the reader. registry.register('copy-files-from-a-to-b', require('some-package/copy-job')); const scheduler = new SimpleScheduler(registry); // A rudimentary backup system. const job = scheduler.schedule('schedule-job-on-the-hour', { name: 'copy-files-from-a-to-b', argument: { from: '/some-directory/to/backup', to: '/volumes/usb-key', }, }); job.output.subscribe((x) => console.log(x)); ``` -------------------------------- ### Manual setup in shell startup file Source: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/completion/long-description.md Add this to your shell startup file (e.g., .bashrc) to load Angular CLI autocompletion only for interactive shells. This gives you control over where the configuration lives, unlike the automatic `ng completion` setup. ```bash if [[ $- == *i* ]]; then source <(ng completion script) fi ``` -------------------------------- ### Example globals and locals JSON Source: https://github.com/angular/angular-cli/blob/main/docs/design/ngConfig.md Shows sample global and local configuration objects used to illustrate the proxy behavior. The local config overrides some values and adds new ones. ```json // Global { "key1": { "key2": { "value": 0, "value2": 1 } } } // Local { "key1": { "key2": { "value2": 2, "value3": 3 } } } ``` -------------------------------- ### Test setup using TEST_TMPDIR Source: https://github.com/angular/angular-cli/blob/main/AGENTS.md Use this TypeScript test setup to create a temporary directory inside Bazel's TEST_TMPDIR. It asserts that TEST_TMPDIR is set and creates a unique subdirectory for the test. Never fall back to os.tmpdir() because Bazel runs tests in hermetic sandboxes. ```typescript import assert from 'node:assert'; import { mkdtemp } from 'node:fs/promises'; import { join } from 'node:path'; describe('...', () => { let tempRoot: string; beforeAll(async () => { const baseTmpDir = process.env['TEST_TMPDIR']; assert(baseTmpDir, 'TEST_TMPDIR is not set'); tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-test-')); }); }); ``` -------------------------------- ### SimpleJobRegistry usage Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/README.md Example of creating a job handler, registering it in a SimpleJobRegistry, and scheduling it. ```typescript import { jobs } from '@angular-devkit/core'; const add = jobs.createJobHandler((argument) => argument.reduce((total, curr) => total + curr, 0), ); // Register the job in a SimpleJobRegistry. Different registries have different API. const registry = new jobs.SimpleJobRegistry(); const scheduler = new SimpleJobScheduler(registry); registry.register(add, { name: 'add', argument: { type: 'array', items: { type: 'number' } }, output: { type: 'number' }, }); scheduler.schedule('add', [1, 2, 3, 4]); ``` -------------------------------- ### Install https-proxy-agent Source: https://github.com/angular/angular-cli/wiki/stories-proxy Installs the https-proxy-agent package as a dev dependency for corporate proxy support. ```bash npm install --save-dev https-proxy-agent ``` -------------------------------- ### Start the build with ng build --watch Source: https://github.com/angular/angular-cli/wiki/stories-disk-serve Run this command in the first terminal to compile the application to the `dist` folder in watch mode. It will rebuild on file saves. ```bash ng build --watch ``` -------------------------------- ### Install less compiler Source: https://github.com/angular/angular-cli/blob/main/docs/design/third-party-libraries.md Installs the less package to enable compilation of CSS files with .less extensions. ```sh $ ng install less ``` -------------------------------- ### Create .browserslistrc file Source: https://github.com/angular/angular-cli/wiki/stories-autoprefixer Create a file named `.browserslistrc` in the project directory with this content to specify the target browsers. The example includes a comment and lists `> 1%` and `last 2 versions`. ```text ### Supported Browsers > 1% last 2 versions ``` -------------------------------- ### Automated setup output and activation command Source: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/completion/long-description.md Shows the terminal output when enabling autocompletion via the CLI prompt. After appending the setup to your shell config, restart the terminal or run `source <(ng completion script)` to activate it in the current session. ```bash $ ng serve ? Would you like to enable autocompletion? This will set up your terminal so pressing TAB while typing Angular CLI commands will show possible options and autocomplete arguments. (Enabling autocompletion will modify configuration files in your home directory.) Yes Appended `source <(ng completion script)` to `/home/my-username/.bashrc`. Restart your terminal or run: source <(ng completion script) to autocomplete `ng` commands. # Serve output... ``` -------------------------------- ### Correct Import Path Convention Source: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/mcp/resources/ai-tutor.md Example of a correct import statement following v20 naming conventions. ```typescript import { RecipeList } from './recipe-list/recipe-list'; ``` -------------------------------- ### Build all packages locally Source: https://github.com/angular/angular-cli/blob/main/AGENTS.md Run this command to create a local build of all packages in the repository. ```shell pnpm build --local ``` -------------------------------- ### Start development server with ng serve Source: https://github.com/angular/angular-cli/blob/main/tests/e2e/assets/20.0-project/README.md Runs the Angular development server. After running, open http://localhost:4200/ in a browser; the app automatically reloads on source file changes. ```bash ng serve ``` -------------------------------- ### Adding a staging environment configuration Source: https://github.com/angular/angular-cli/wiki/stories-application-environments Example of adding a custom staging configuration to the fileReplacements section in angular.json. ```json "configurations": { "production": { ... }, "staging": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.staging.ts" } ] } } ``` -------------------------------- ### Run npm run hmr to start dev server Source: https://github.com/angular/angular-cli/wiki/stories-configure-hmr Run npm run hmr to start the development server with HMR enabled. Webpack will display a notice that HMR is enabled for the dev server. ```bash $ npm run hmr ``` -------------------------------- ### Complete server.ts implementation Source: https://github.com/angular/angular-cli/wiki/stories-universal-rendering A full example of a server.ts file at the root level to serve the Angular application using Express and Universal. ```typescript // These are important and needed before anything else import 'zone.js/dist/zone-node'; import 'reflect-metadata'; import { renderModuleFactory } from '@angular/platform-server'; import { enableProdMode } from '@angular/core'; import * as express from 'express'; import { join } from 'path'; import { readFileSync } from 'fs'; // Import module map for lazy loading import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader'; // Faster server renders w/ Prod mode (dev mode never needed) enableProdMode(); // Express server const app = express(); const PORT = process.env.PORT || 4000; const DIST_FOLDER = join(process.cwd(), 'dist'); // Our index.html we'll use as our template const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString(); app.engine('html', (_, options, callback) => { renderModuleFactory(AppServerModuleNgFactory, { // Our index.html document: template, url: options.req.url, // DI so that we can get lazy-loading to work differently (since we need it to just instantly render it) extraProviders: [ provideModuleMap(LAZY_MODULE_MAP) ] }).then(html => { callback(null, html); }); }); app.set('view engine', 'html'); app.set('views', join(DIST_FOLDER, 'browser')); // Server static files from /browser app.get('*.*', express.static(join(DIST_FOLDER, 'browser'))); // All regular routes use the Universal engine app.get('*', (req, res) => { res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req }); }); // Start up the Node server app.listen(PORT, () => { console.log(`Node server listening on http://localhost:${PORT}`); }); ``` -------------------------------- ### Create and serve a new Angular project Source: https://github.com/angular/angular-cli/wiki/Home Generates a new Angular project and starts a development server. Navigate to http://localhost:4200/; the app automatically reloads on source file changes. ```bash ng new my-project cd my-project ng serve ``` -------------------------------- ### Run all unit and integration tests Source: https://github.com/angular/angular-cli/blob/main/AGENTS.md Runs all unit and integration tests in the packages directory. ```shell pnpm bazel test //packages/... ``` -------------------------------- ### Query all test targets Source: https://github.com/angular/angular-cli/blob/main/AGENTS.md Queries all test targets under //packages/... ```shell pnpm bazel query "tests(//packages/...)" ``` -------------------------------- ### Install global Angular CLI release Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md Installs the latest CLI release globally. The CLI will automatically detect and use a local build when running `ng` commands in the example project. ```shell npm install -g @angular/cli ``` -------------------------------- ### Import Bootstrap in styles.scss Source: https://github.com/angular/angular-cli/wiki/stories-include-bootstrap Imports variables and Bootstrap in styles.scss for the SASS setup. ```sass @import 'variables'; @import '../node_modules/bootstrap/scss/bootstrap'; ``` -------------------------------- ### Implementing a Standard Signal Form Component Source: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/mcp/resources/ai-tutor.md A complete example showing form definition, template binding with the [field] directive, and submission handling using the submit utility. ```typescript // src/app/example/example.ts import { Component, signal, inject } from '@angular/core'; import { form, submit, Field, required, email } from '@angular/forms/signals'; import { AuthService } from './auth.service'; @Component({ selector: 'app-example', imports: [Field], template: `
@if (loginForm.email().touched() && loginForm.email().invalid()) {

@for (error of loginForm.email().errors(); track error.kind) { {{ error.message }} }

}
`, }) export class Example { private readonly authService = inject(AuthService); protected readonly loginModel = signal({ email: '', password: '' }); protected readonly loginForm = form(this.loginModel, (s) => { required(s.email, { message: 'Required' }); email(s.email, { message: 'Invalid email' }); }); protected async save(event: Event): Promise { event.preventDefault(); await submit(this.loginForm, async () => { await this.authService.login(this.loginForm().value()); this.loginForm().reset(); this.loginModel.set({ email: '', password: '' }); }); } } ``` -------------------------------- ### Config proxy usage example Source: https://github.com/angular/angular-cli/blob/main/docs/design/ngConfig.md Demonstrates how the `local` and `global` proxies behave: local defers to global for missing values, local overrides global, and setting values only affects the appropriate config. `config.save()` commits changes if any. ```typescript const config = new Config(/* ... */); console.log(config.local.key1.key2.value); // 0, even if it doesn't exist. console.log(config.local.key1.key2.value2); // 2, local overrides. console.log(config.local.key1.key2.value3); // 3. console.log(config.local.key1.key2.value4); // Schema's default value. console.log(config.global.key1.key2.value); // 0. console.log(config.global.key1.key2.value2); // 1, only global. console.log(config.global.key1.key2.value3); // Schema's default value. config.local.key1.key2.value = 1; // Now the value is 1 inside the local. Global stays the same. config.local.key1.key2.value3 = 5; // The global config isn't modified. config.global.key1.key2.value4 = 99; // The local config stays the same. console.log(config.local.key1.key2.value4); // 99, the global value. config.save(); // Commits if there's a change to global and/or local. ``` -------------------------------- ### Create a higher-order job function Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/architecture.md This example demonstrates creating a job function that wraps another job to run it on the hour, every hour. ```javascript // Runs a job on the hour, every hour, regardless of how long the job takes. // This creates a job function that can be registered by itself. function scheduleJobOnTheHour(jobFunction) { return function (argument, context) { return new Observable((observer) => { let timeout = 0; function _timeoutToNextHour() { // Just wait until the next hour. const t = new Date(); const secondsToNextHour = 3600 - t.getSeconds() - t.getMinutes() * 60; timeout = setTimeout(_scheduleJobAndWaitAnHour, secondsToNextHour); } function _scheduleJobAndWaitAnHour() { jobFunction(argument, context).subscribe( (message) => observer.next(message), (error) => observer.error(error), // Do not forward completion, but use it to schedule the next job run. () => { _timeoutToNextHour(); }, ); } // Kick off by waiting for next hour. _timeoutToNextHour(); return () => clearTimeout(timeout); }); }; } ``` -------------------------------- ### Create a new git branch Source: https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md Start your changes by creating a new branch from the main branch. ```shell git checkout -b my-fix-branch main ``` -------------------------------- ### package.json scripts section Source: https://github.com/angular/angular-cli/wiki/stories-1.0-update This snippet shows the simplified scripts section from the updated package.json, defining commands for ng, start, build, test, lint, and e2e. ```json "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, ``` -------------------------------- ### Create a build Source: https://github.com/angular/angular-cli/wiki/build Executes a build, storing artifacts in the dist/ directory by default. ```bash ng build ``` -------------------------------- ### Verify Font Awesome installation in app.component.html Source: https://github.com/angular/angular-cli/wiki/stories-include-font-awesome Add an icon to the app component template to verify that Font Awesome is working correctly. ```html

{{title}}

``` -------------------------------- ### WindowService with getWidth method Source: https://github.com/angular/angular-cli/blob/main/docs/specifications/universal-gotchas.md Defines an injectable WindowService that accesses the browser window to get its width. This is the base service that will be replaced on the server. ```TypeScript // window-service.ts import { Injectable } from '@angular/core'; @Injectable() export class WindowService { getWidth(): number { return window.innerWidth; } } ``` -------------------------------- ### Import and use typeless package Source: https://github.com/angular/angular-cli/wiki/stories-third-party-lib Import and use the library in your component or file after adding the manual typings. This example shows importing the module and calling a method. ```typescript import * as typelessPackage from 'typeless-package'; typelessPackage.method(); ``` -------------------------------- ### Create Angular workspace with npm Source: https://github.com/angular/angular-cli/blob/main/packages/angular/create/README.md Scaffold an Angular CLI workspace using npm without a global Angular CLI installation. Supports all ng new options and features. ```bash npm init @angular@latest [project-name] -- [...options] ``` -------------------------------- ### Install @angularclass/hmr as dev-dependency Source: https://github.com/angular/angular-cli/wiki/stories-configure-hmr Install the @angularclass/hmr module as a dev-dependency using npm. ```bash $ npm install --save-dev @angularclass/hmr ``` -------------------------------- ### Create Angular workspace with bun Source: https://github.com/angular/angular-cli/blob/main/packages/angular/create/README.md Scaffold an Angular CLI workspace using bun without a global Angular CLI installation. Supports all ng new options and features. ```bash bun create @angular [project-name] [...options] ``` -------------------------------- ### Create new Angular project and navigate into it Source: https://github.com/angular/angular-cli/wiki/stories-include-angularfire Commands to create a new Angular project and change into its directory. ```bash $ ng new my-app $ cd my-app ``` -------------------------------- ### Multiple apps configuration in .angular-cli.json Source: https://github.com/angular/angular-cli/wiki/stories-multiple-apps Example of adding a second application to the apps array by copying the object and modifying specific properties like main, polyfills, test, and prefix. ```json "apps": [ { "root": "src", ... "main": "main.ts", "polyfills": "polyfills.ts", "test": "test.ts", "tsconfig": "tsconfig.app.json", "testTsconfig": "tsconfig.spec.json", "prefix": "app", ... }, { "root": "src", ... "main": "main2.ts", "polyfills": "polyfills2.ts", "test": "test2.ts", "tsconfig": "tsconfig.app.json", "testTsconfig": "tsconfig.spec.json", "prefix": "app2", ... } ], ``` -------------------------------- ### Install AngularFire2 and Firebase dependencies Source: https://github.com/angular/angular-cli/wiki/stories-include-angularfire Install the required npm packages for AngularFire2 and Firebase. ```bash $ npm install --save angularfire2 firebase ``` -------------------------------- ### Create Angular workspace with pnpm Source: https://github.com/angular/angular-cli/blob/main/packages/angular/create/README.md Scaffold an Angular CLI workspace using pnpm without a global Angular CLI installation. Supports all ng new options and features. ```bash pnpm create @angular [project-name] [...options] ``` -------------------------------- ### Enter WSL environment Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md Run this command to enter the WSL environment after restarting your machine. ```bash wsl ``` -------------------------------- ### Build Angular CLI locally with pnpm build --local Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md Run from the root of the cloned repository to generate tarballs in the `dist/` directory. Requires Node v22.22.3 or higher and pnpm installed. ```shell pnpm build --local ``` -------------------------------- ### Build a Schematic Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/README.md Command to initiate a walkthrough for building a new schematic. ```bash $ schematics schematic --name ``` -------------------------------- ### Define appPrompt configuration in package.json Source: https://github.com/angular/angular-cli/blob/main/docs/design/third-party-libraries.md Example of defining user prompts and default values within the angular-cli configuration object. The default value type is used to convert user input, and special strings like ${homepage} are replaced with values from package.json. ```typescript { // ... "angular-cli": { "appPrompt": { "number": { "prompt": "Please enter a number:", "defaultValue": 0 }, "url": { "prompt": "URL of your website:", "defaultValue": "${homepage}" } } } } ``` -------------------------------- ### Add browserslist property to package.json Source: https://github.com/angular/angular-cli/wiki/stories-autoprefixer Add this `browserslist` property to your `package.json` file to specify which browsers Autoprefixer should target. The example uses `> 1%` and `last 2 versions` to cover browsers with over 1% usage and the last two versions of each browser. ```json "browserslist": [ "> 1%", "last 2 versions" ] ``` -------------------------------- ### Build server bundle with Angular CLI Source: https://github.com/angular/angular-cli/wiki/stories-universal-rendering Use the ng run command to build the server bundle for your project, which outputs to the dist directory. ```bash # This builds your project using the server target, and places the output # in dist/your-project-name-server/ $ ng run your-project-name:server Date: 2017-07-24T22:42:09.739Z Hash: 9cac7d8e9434007fd8da Time: 4933ms chunk {0} main.js (main) 9.49 kB [entry] [rendered] chunk {1} styles.css (styles) 0 bytes [entry] [rendered] ``` -------------------------------- ### Usage example: adding an option to a build target Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/core/README.md Shows how to add an option property to a build target for an application using the workspaces API. It reads a workspace, retrieves a project and its build target, sets the optimization option, and writes the workspace back. ```typescript import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { workspaces } from '@angular-devkit/core'; async function demonstrate() { const host = workspaces.createWorkspaceHost(new NodeJsSyncHost()); const { workspace } = await workspaces.readWorkspace('path/to/workspace/directory/', host); const project = workspace.projects.get('my-app'); if (!project) { throw new Error('my-app does not exist'); } const buildTarget = project.targets.get('build'); if (!buildTarget) { throw new Error('build target does not exist'); } buildTarget.options.optimization = true; await workspaces.writeWorkspace(workspace, host); } demonstrate(); ``` -------------------------------- ### Create mock-recipes.ts file Source: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/mcp/resources/ai-tutor.md Command to create the mock recipes file for the application. ```bash touch src/app/mock-recipes.ts ``` -------------------------------- ### Initialize Angular application with routing Source: https://github.com/angular/angular-cli/wiki/stories-app-shell Create a new Angular project with routing enabled to support the App Shell feature. ```bash ng new my-app --routing ``` -------------------------------- ### Install angularfire2 with quiet mode Source: https://github.com/angular/angular-cli/blob/main/docs/design/third-party-libraries.md Installs angularfire2 using the --quiet flag to skip all prompts and use default values. ```sh $ ng install angularfire2 --quiet ``` -------------------------------- ### Basic ng build command syntax Source: https://github.com/angular/angular-cli/wiki/build The standard syntax for running a build for a specific project. ```bash ng build [project] ``` -------------------------------- ### Trigger a release build locally Source: https://github.com/angular/angular-cli/blob/main/docs/process/release.md Commands to set up the environment and build the release locally from the main branch. ```shell nvm install pnpm install --frozen-lockfile pnpm ng-dev release build ``` -------------------------------- ### Install npm dependencies Source: https://github.com/angular/angular-cli/wiki/Upgrading-from-Beta.10-to-Beta.14 Install npm dependencies that your application uses, such as Angular Material 2, Angularfire2, Bootstrap, Firebase, jQuery, or Moment. ```bash npm install --save ${LIBRARY} ``` -------------------------------- ### Install Bootstrap dependencies with npm Source: https://github.com/angular/angular-cli/wiki/stories-global-lib Install jquery, popper.js, and bootstrap packages via npm to use Bootstrap 4 in an Angular CLI v6 project. ```bash npm install jquery --save npm install popper.js --save npm install bootstrap --save ``` -------------------------------- ### angular.json production budgets configuration Source: https://github.com/angular/angular-cli/wiki/stories-budgets Example of adding a budgets array to the production configuration in angular.json. The budgets array is empty in this example, but can be filled with budget definitions as described on the page. ```json { ... "configurations": { "production": { ... budgets: [] } } } ``` -------------------------------- ### Install only the Angular CLI tarball for ng update testing Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md When testing `ng update`, install only the CLI tarball to avoid updating the framework (`@angular/core`) to the latest version. The rest of the project remains to be upgraded with `ng update`. ```shell npm install -D ${CLI_REPO}/dist/_angular_cli.tgz ``` -------------------------------- ### Basic ng serve command Source: https://github.com/angular/angular-cli/wiki/serve The standard command to build and serve an Angular project. ```bash ng serve [project] ``` -------------------------------- ### SchematicTestRunner.logger getter Source: https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/testing/index.api.md Gets the logger used by the runner. ```APIDOC ## SchematicTestRunner.logger getter ### Description Gets the logger used by the runner. ### Signature get logger(): logging.Logger ### Returns logging.Logger - The logger instance. ``` -------------------------------- ### UnitTestTree.files getter Source: https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/testing/index.api.md Gets the list of file paths in the tree. ```APIDOC ## UnitTestTree.files getter ### Description Gets the list of file paths in the tree. ### Signature get files(): string[] ### Returns string[] - An array of file paths. ``` -------------------------------- ### Build and publish schematics package Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/blank/project-files/README.md Run these commands to build the project and publish it to NPM. The build step is required before publishing. ```bash npm run build ``` ```bash npm publish ``` -------------------------------- ### SchematicTestRunner.tasks getter Source: https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/testing/index.api.md Gets the list of tasks scheduled by the runner. ```APIDOC ## SchematicTestRunner.tasks getter ### Description Gets the list of tasks scheduled by the runner. ### Signature get tasks(): TaskConfiguration[] ### Returns TaskConfiguration[] - An array of task configurations. ``` -------------------------------- ### SchematicTestRunner.engine getter Source: https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/testing/index.api.md Gets the schematic engine used by the runner. ```APIDOC ## SchematicTestRunner.engine getter ### Description Gets the schematic engine used by the runner. ### Signature get engine(): SchematicEngine<{}, {}> ### Returns SchematicEngine<{}, {}> - The schematic engine instance. ``` -------------------------------- ### List unit test targets with Bazel query Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md Queries Bazel for all test targets under //packages/... ```shell pnpm bazel query "tests(//packages/...)" ``` -------------------------------- ### NodeModuleJobRegistry usage Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/README.md Example of scheduling a job using a NodeModuleJobRegistry by referencing a package and export. ```typescript declare const registry: NodeModuleJobRegistry; const scheduler = new SimpleJobScheduler(registry); scheduler.schedule('some-node-package#someExport', 'input'); ``` -------------------------------- ### Configure CSS for Flex Layout Sample Source: https://github.com/angular/angular-cli/wiki/stories-include-angular-flex Add these styles to src/app/app.component.css to visualize the flex layout containers and items. ```css [fxLayout="column"] { border: 1px solid;padding:4px; margin-top:50px; }, [fxFlex]{ padding:5px;}, h3 { padding-top:20px; }, .header { background-color: lightyellow; }, .left { background-color: lightblue; }, .right { background-color: pink; } ``` -------------------------------- ### Create models.ts file Source: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/mcp/resources/ai-tutor.md Command to create the models file for the Smart Recipe Box application. ```bash touch src/app/models.ts ``` -------------------------------- ### Generate App Shell Source: https://github.com/angular/angular-cli/wiki/stories-app-shell Run the generator to create the app shell, specifying the client project and the universal server project. ```bash ng generate app-shell --client-project my-app --universal-project server-app ``` -------------------------------- ### Incorrect Import Path Convention Source: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/mcp/resources/ai-tutor.md Example of an incorrect import statement that violates v20 naming conventions. ```typescript import { RecipeListComponent } from './recipe-list/recipe-list.component'; ``` -------------------------------- ### Create new Angular project with SASS Source: https://github.com/angular/angular-cli/wiki/stories-include-bootstrap Commands to create a new Angular project with SASS style and navigate into it. ```bash ng new my-app --style=scss cd my-app ``` -------------------------------- ### Define ng-update in package.json Source: https://github.com/angular/angular-cli/blob/main/docs/specifications/update.md Example configuration for a library to specify update requirements and the path to its migration collection. ```json { "ng-update": { "requirements": { "my-lib": "^5" }, "migrations": "./migrations/migration-collection.json" } } ``` -------------------------------- ### Adding custom variables to environment.ts Source: https://github.com/angular/angular-cli/wiki/stories-application-environments Example of adding additional properties like apiUrl to the environment object. ```TypeScript export const environment = { production: false, apiUrl: 'http://my-api-url' }; ``` -------------------------------- ### Migrate environments to environmentSource (Before and After) Source: https://github.com/angular/angular-cli/wiki/stories-1.0-update The 'source' entry inside environments is replaced by a new top-level 'environmentSource' entry. The 'dev' and 'prod' entries remain inside environments. ```json "environments": { "source": "environments/environment.ts", "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts" } ``` ```json "environmentSource": "environments/environment.ts", "environments": { "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts" } ``` -------------------------------- ### Create new migration project Source: https://github.com/angular/angular-cli/wiki/Upgrading-from-Beta.10-to-Beta.14 Create a new migration project to use as a template for the webpack-based build. ```bash ng new migration-project ``` -------------------------------- ### Upgrade Angular CLI globally Source: https://github.com/angular/angular-cli/wiki/Upgrading-from-Beta.10-to-Beta.14 Upgrade the global Angular CLI to the latest version before starting the migration. ```bash npm uninstall -g angular-cli npm cache clean npm install -g angular-cli@latest ``` -------------------------------- ### Install new @angular/cli Source: https://github.com/angular/angular-cli/wiki/stories-1.0-update Commands to update the global and local `@angular/cli` packages to the latest version and restore dependencies. ```bash npm install -g @angular/cli@latest # Global package npm install --save-dev @angular/cli@latest # Local package npm install # Restore removed dependencies ``` -------------------------------- ### Basic proxy.conf.json Source: https://github.com/angular/angular-cli/wiki/stories-proxy Creates a proxy configuration file that forwards requests to /api to http://localhost:3000. The secure: false option is used for local HTTP targets. ```json { "/api": { "target": "http://localhost:3000", "secure": false } } ``` -------------------------------- ### Publish a library Source: https://github.com/angular/angular-cli/wiki/stories-create-library Builds the library, changes to the dist output directory, and publishes to npm. Requires an npm account if not already registered. ```bash ng build my-lib cd dist/my-lib npm publish ``` -------------------------------- ### Define migration collection Source: https://github.com/angular/angular-cli/blob/main/docs/specifications/update.md Example of a migration collection file mapping migration versions to their respective factory paths. ```json { "schematics": { "migration-01": { "version": "6", "factory": "./update-6" }, "migration-02": { "version": "6.2", "factory": "./update-6_2" }, "migration-03": { "version": "6.3", "factory": "./update-6_3" }, "migration-04": { "version": "7", "factory": "./update-7" }, "migration-05": { "version": "8", "factory": "./update-8" } } } ``` -------------------------------- ### SimpleScheduler Source: https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/architect/index.api.md A scheduler for jobs. Allows scheduling, checking existence, and getting descriptions of jobs. ```APIDOC ## SimpleScheduler ### Description A scheduler for jobs. Allows scheduling, checking existence, and getting descriptions of jobs. ### Constructor `constructor(_jobRegistry: Registry, _schemaRegistry?: schema.SchemaRegistry)` ### Methods #### getDescription Gets the description of a job by name. **Signature:** `getDescription(name: JobName): Observable` **Parameters:** - **name** (JobName) - Required - The name of the job. **Returns:** Observable #### has Checks if a job exists by name. **Signature:** `has(name: JobName): Observable` **Parameters:** - **name** (JobName) - Required - The name of the job. **Returns:** Observable #### pause Pauses the scheduler and returns a function to resume. **Signature:** `pause(): () => void` **Returns:** () => void #### schedule Schedules a job. **Signature:** `schedule(name: JobName, argument: A, options?: ScheduleJobOptions): Job` **Parameters:** - **name** (JobName) - Required - The name of the job. - **argument** (A) - Required - The argument to pass to the job. - **options** (ScheduleJobOptions) - Optional - Scheduling options. **Returns:** Job ``` -------------------------------- ### Merge an approved PR Source: https://github.com/angular/angular-cli/blob/main/AGENTS.md Merges an approved PR into its targeted branches. ```shell pnpm ng-dev pr merge ``` -------------------------------- ### Create an Observable job stream Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/architecture.md An example of a basic Observable that emits values from 1 to 10 at one-second intervals before completing. ```javascript const output1To10EverySecond = function (subscriber) { let t = 0; const i = setInterval(() => { t++; subscriber.next(t); if (t === 10) { subscriber.complete(t); } }, 1000); return () => clearInterval(i); }; const stream$ = new Observable(output1To10EverySecond); // Start the function, and output 1 to 100, once per line. stream$.subscribe((x) => console.log(x)); ``` -------------------------------- ### Scheduler interface pause method Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/README.md The pause method stops the scheduler from starting new jobs and returns a resume function. ```typescript interface Scheduler { /** * Pause the scheduler, temporary queueing _new_ jobs. Returns a resume function that should be * used to resume execution. If multiple `pause()` were called, all their resume functions must * be called before the Scheduler actually starts new jobs. Additional calls to the same resume * function will have no effect. * * Jobs already running are NOT paused. This is pausing the scheduler only. * * @returns A function that can be run to resume the scheduler. If multiple `pause()` calls * were made, all their return function must be called (in any order) before the * scheduler can resume. */ pause(): () => void; } ``` -------------------------------- ### After: Using an img tag instead of file-loader Source: https://github.com/angular/angular-cli/blob/main/CHANGELOG.md Shows the replacement approach after removing file-loader: use an HTML img tag with the asset path. ```HTML ``` -------------------------------- ### Run subset of E2E tests Source: https://github.com/angular/angular-cli/blob/main/AGENTS.md Runs a subset of E2E tests with a filter. ```shell pnpm bazel test //tests:e2e_node22 --config=e2e --test_filter="" ``` -------------------------------- ### Build application with App Shell Source: https://github.com/angular/angular-cli/wiki/stories-app-shell Execute the app-shell target to build the application with the shell content. ```bash ng run my-app:app-shell ``` -------------------------------- ### Add polyfills entry in apps[0] Source: https://github.com/angular/angular-cli/wiki/stories-1.0-update Insert this entry between 'main' and 'test' in the apps[0] configuration. Then remove 'import './polyfills.ts';' from src/main.ts and src/test.ts. ```json "main": "main.ts", "polyfills": "polyfills.ts", "test": "test.ts", ``` -------------------------------- ### Link DevKit binaries Source: https://github.com/angular/angular-cli/blob/main/scripts/README.md Run this command to link the binaries in the repository, enabling the use of the devkit-admin command. ```bash $ npm link ``` -------------------------------- ### Provide additional e2e_runner options with --test_arg Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md Passes extra options to the e2e runner, for example to select a package manager. ```shell --test_arg="--package-manager=yarn" ``` -------------------------------- ### Run a subset of unit tests with Bazel target Source: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md Runs a specific Bazel test target, for example the schematics Angular tests. ```shell pnpm bazel test //packages/schematics/angular:test ``` -------------------------------- ### Run ng lint command Source: https://github.com/angular/angular-cli/wiki/lint Basic syntax to execute the linting process for a specified project. ```bash ng lint [project] ``` -------------------------------- ### Create src/main.server.ts Source: https://github.com/angular/angular-cli/wiki/stories-universal-rendering Export the AppServerModule from the server main file. ```typescript export { AppServerModule } from './app/app.server.module'; ``` -------------------------------- ### Expected dist directory structure Source: https://github.com/angular/angular-cli/wiki/stories-universal-rendering The expected directory structure after running the build process. ```text /dist/ /browser/ /server/ ``` -------------------------------- ### Copy app files from old project Source: https://github.com/angular/angular-cli/wiki/stories-moving-into-the-cli Copy the application source files from the old project into the new CLI project. The commands assume the old project is in a sibling folder named old-awesome-app and that the new project is in the current directory. ```bash cp -r ../old-awesome-app/src/app ./src/app cp ../old-awesome-app/src/index.html ./src/index.html cp ../old-awesome-app/src/styles.css ./src/styles.css cp -r ../old-awesome-app/e2e ./e2e/ ``` -------------------------------- ### AppModule declaring ExampleComponent Source: https://github.com/angular/angular-cli/blob/main/docs/specifications/universal-gotchas.md Base app module that declares the ExampleComponent, keeping platform-agnostic code. ```TypeScript // app.module.ts import {NgModule} from '@angular/core'; import {ExampleComponent} from './example.component'; @NgModule({ declarations: [ExampleComponent], }) ``` -------------------------------- ### Create a new Angular workspace Source: https://github.com/angular/angular-cli/blob/main/README.md Initializes a new Angular workspace with the specified project name. ```bash ng new [PROJECT NAME] ``` -------------------------------- ### Apply Memoization Strategy Source: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/architect/src/jobs/README.md Use jobs.strategy.memoize() to create a job that reuses results when inputs match, or starts a new job if inputs differ. ```typescript // Same input and output as above. export const add = jobs.strategy.memoize()( jobs.createJobHandler((argument) => argument.reduce((total, curr) => total + curr, 0), ), ); ``` -------------------------------- ### Schedule builder with target property Source: https://github.com/angular/angular-cli/blob/main/CHANGELOG.md Calling BuilderContext.scheduleBuilder() with a builder from @angular-devkit/build-angular now requires passing the target property in the 3rd argument, as shown in this TypeScript example. ```typescript context.scheduleBuilder('@angular-devkit/build-angular:ng-packagr', options, { target: context.target, }); ```