### Basic Connected Overlay Example
Source: https://angular.dev/guide/aria/api/cdk/overlay/CdkConnectedOverlay
Demonstrates the basic setup of a connected overlay using CdkConnectedOverlay. This example shows how to connect an overlay to a button, allowing it to open and close on click.
```html
Content to display in the overlay
```
--------------------------------
### Customizable Setup Function
Source: https://angular.dev/guide/testing/components-basics
Define a reusable `setup` function to configure `TestBed` and create components, allowing for parameter customization.
```typescript
function setup(providers?: StaticProviders[]): ComponentFixture {
TestBed.configureTestingModule({providers});
return TestBed.createComponent(Banner);
}
```
--------------------------------
### Install Vitest Browser Preview Provider
Source: https://angular.dev/guide/testing
Install the `@vitest/browser-preview` provider for use in WebContainer environments like StackBlitz. This provider is not intended for CI/CD.
```bash
npm install --save-dev @vitest/browser-preview
```
--------------------------------
### Load Component Harnesses in Tests
Source: https://angular.dev/guide/testing/using-component-harnesses
This example demonstrates loading harnesses for different components within a test setup. It shows how to use `harnessForFixture` for the root component and `loader` or `rootLoader` for child components based on their DOM location.
```typescript
let fixture: ComponentFixture;
let loader: HarnessLoader;
let rootLoader: HarnessLoader;
beforeEach(() => {
fixture = TestBed.createComponent(MyDialogButton);
loader = TestbedHarnessEnvironment.loader(fixture);
rootLoader = TestbedHarnessEnvironment.documentRootLoader(fixture);
});
it('loads harnesses', async () => {
// Load a harness for the bootstrapped component with `harnessForFixture`
dialogButtonHarness = await TestbedHarnessEnvironment.harnessForFixture(
fixture,
MyDialogButtonHarness,
);
// The button element is inside the fixture's root element, so we use `loader`.
const buttonHarness = await loader.getHarness(MyButtonHarness);
// Click the button to open the dialog
await buttonHarness.click();
// The dialog is appended to `document.body`, outside of the fixture's root element,
// so we use `rootLoader` in this case.
const dialogHarness = await rootLoader.getHarness(MyDialogHarness);
// ... make some assertions
});
```
--------------------------------
### Install Vitest and jsdom
Source: https://angular.dev/guide/testing/migrating-to-vitest
Install Vitest and a DOM emulation library like jsdom for faster test execution in a simulated browser environment within Node.js.
```bash
npm install --save-dev vitest jsdom
```
--------------------------------
### Install Karma and Jasmine Packages
Source: https://angular.dev/guide/testing/karma
Install the necessary npm packages for Karma and Jasmine testing in an existing project.
```bash
npm install --save-dev karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine
```
--------------------------------
### Install Vitest Coverage Package
Source: https://angular.dev/guide/testing/code-coverage
Install the `@vitest/coverage-v8` package as a development dependency to enable code coverage reporting with Vitest.
```bash
npm install --save-dev @vitest/coverage-v8
```
--------------------------------
### Basic Menu Item Example
Source: https://angular.dev/guide/aria/menubar
Demonstrates a simple menu item with a label and shortcut. Use this for basic actions within a menu.
```html
strikethrough_sStrikethroughβ§βX
```
--------------------------------
### Basic FormGroup Example
Source: https://angular.dev/guide/forms/typed-forms
A simple example of a `FormGroup` for a user login form. This demonstrates the basic structure for typed reactive forms.
```typescript
const login = new FormGroup({
email: new FormControl(''),
password: new FormControl(''),
});
```
--------------------------------
### Practical Example: Logger Substitution
Source: https://angular.dev/guide/di/defining-dependency-providers
Demonstrates how to substitute logger implementations to extend functionality. This example shows a base logger, an enhanced logger with timestamps, and a logger that includes user context, all provided via useClass.
```typescript
import {Injectable, Component, inject} from '@angular/core';
// Base logger
@Injectable()
export class Logger {
log(message: string) {
console.log(message);
}
}
// Enhanced logger with timestamp
@Injectable()
export class BetterLogger extends Logger {
override log(message: string) {
super.log(`[${new Date().toISOString()}] ${message}`);
}
}
// Logger that includes user context
@Injectable()
export class EvenBetterLogger extends Logger {
private userService = inject(UserService);
override log(message: string) {
const name = this.userService.user.name;
super.log(`Message to ${name}: ${message}`);
}
}
// In your component
@Component({
selector: 'app-example',
providers: [
UserService, // EvenBetterLogger needs this
{provide: Logger, useClass: EvenBetterLogger},
],
})
export class Example {
private logger = inject(Logger); // Gets EvenBetterLogger instance
}
```
--------------------------------
### Standalone DashboardHero Component Setup
Source: https://angular.dev/guide/testing/components-scenarios
Sets up a test environment for the DashboardHero component. It creates a component fixture, gets the instance, finds the hero element, mocks a hero object, and sets the input property.
```typescript
let fixture: ComponentFixture;
let comp: DashboardHero;
let heroDe: DebugElement;
let heroEl: HTMLElement;
let expectedHero: Hero;
beforeEach(async () => {
fixture = TestBed.createComponent(DashboardHero);
comp = fixture.componentInstance;
// find the hero's DebugElement and element
heroDe = fixture.debugElement.query(By.css('.hero'));
heroEl = heroDe.nativeElement;
// mock the hero supplied by the parent component
expectedHero = {id: 42, name: 'Test Name'};
// simulate the parent setting the input property with that hero
fixture.componentRef.setInput('hero', expectedHero);
// wait for initial data binding
await fixture.whenStable();
});
```
--------------------------------
### Install Tailwind CSS and PostCSS Dependencies
Source: https://angular.dev/guide/tailwind
Install Tailwind CSS and its peer dependencies using npm, yarn, pnpm, or bun.
```bash
npm install tailwindcss @tailwindcss/postcss postcss
```
--------------------------------
### Test Host Component Setup
Source: https://angular.dev/guide/testing/components-scenarios
Define a test host component to bind inputs and events to the component under test. This setup is useful for verifying component interactions.
```typescript
@Component({
imports: [DashboardHero],
template: ` `,
})
class TestHost {
hero: Hero = {id: 42, name: 'Test Name'};
selectedHero: Hero | undefined;
onSelected(hero: Hero) {
this.selectedHero = hero;
}
}
```
--------------------------------
### Install Angular CDK
Source: https://angular.dev/guide/drag-drop
Install the Angular Component Dev Kit (CDK) from npm using the Angular CLI. This is a prerequisite for using the drag and drop directives.
```bash
ng add @angular/cdk
```
--------------------------------
### Setup for Banner Component Tests
Source: https://angular.dev/guide/testing/components-scenarios
Initializes the testing environment for the Banner component. It sets up component fixture, instance, and queries the H1 element for assertions. This setup is crucial before running individual tests.
```typescript
let component: Banner;
let fixture: ComponentFixture;
let h1: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(Banner);
component = fixture.componentInstance; // Banner test instance
h1 = fixture.nativeElement.querySelector('h1');
});
```
--------------------------------
### Basic Menu with Submenu Example
Source: https://angular.dev/guide/aria/menu
This example demonstrates how to create a basic menu with a submenu using Angular Material's CDK overlay and menu directives. It includes items like 'Mark as read', 'Snooze', 'Categorize', and 'Archive'. The 'Categorize' item features a submenu.
```html
mark_email_readMark as read
snoozeSnooze
categoryCategorizearrow_right
label_importantMark as important
starStar
labelLabel
archiveArchive
reportReport spam
deleteDelete
```
--------------------------------
### Rendering Example: Visiting /products
Source: https://angular.dev/guide/routing/show-routes-with-outlets
When a user navigates to '/products', Angular renders the `Products` component within the `router-outlet`.
```html
```
--------------------------------
### Basic Grid Structure
Source: https://angular.dev/guide/aria/grid
This example shows the basic structure of a grid with emojis, demonstrating a two-dimensional layout.
```html
π€―| π€―| π€―| β¨| π
---|---|---|---|---
π| π£| π₯
π₯| π―
π₯| π
π| π| π£
π₯| π€―| π£
```
--------------------------------
### Route Definitions Example
Source: https://angular.dev/guide/routing/show-routes-with-outlets
Define your application's routes with paths and associated components. This configuration determines which component is rendered for a given URL.
```typescript
import {Routes} from '@angular/router';
import {Home} from './home';
import {Products} from './products';
const routes: Routes = [
{
path: '',
component: Home,
title: 'Home Page',
},
{
path: 'products',
component: Products,
title: 'Our Products',
},
];
```
--------------------------------
### Debugging with Dependency Path Example
Source: https://angular.dev/guide/di/debugging-and-troubleshooting-di
Shows how to interpret a dependency path in an error message to trace the injection chain and identify where a provider is missing.
```typescript
NullInjectorError: No provider for LoggerStore!
Dependency path: App -> DataStore -> ApiClient -> LoggerStore
```
--------------------------------
### Configuring Overlay Position
Source: https://angular.dev/guide/aria/api/cdk/overlay/CdkConnectedOverlay
Shows how to configure the position of the connected overlay. This example uses `cdkConnectedOverlayPositions` to define fallback positions when the preferred position is not available.
```html
Content to display in the overlay
```
--------------------------------
### Create Actor Instance
Source: https://angular.dev/guide/forms/template-driven-forms
Demonstrates creating a new instance of the `Actor` class and logging its name to the console. This is a basic example of using the data model.
```typescript
const myActress = new Actor(42, 'Marilyn Monroe', 'Singing');
console.log('My actress is called ' + myActress.name); // "My actress is called Marilyn"
```
--------------------------------
### Vertical Tabs Example
Source: https://angular.dev/guide/aria/tabs
Arranges tabs vertically, suitable for sidebars or settings panels. Includes the TypeScript component setup.
```html
videocam
theater_comedy
reviews
Panel 1
```
```typescript
import {Component} from '@angular/core';
import {Tab, Tabs, TabList, TabPanel, TabContent} from '@angular/aria/tabs';
@Component({
selector: 'app-root',
templateUrl: './app.html',
styleUrl: './app.css',
imports: [TabList, Tab, Tabs, TabPanel, TabContent],
})
export class App {}
```
--------------------------------
### Creating Components
Source: https://angular.dev/guide/testing/utility-apis
Create a component instance based on the current TestBed configuration.
```APIDOC
## createComponent
### Description
Creates an instance of a component of type `T` based on the current `TestBed` configuration. After calling this method, the `TestBed` configuration is frozen for the duration of the current spec. Returns a `ComponentFixture`.
### Method
`TestBed.createComponent(component: Type): ComponentFixture`
### Parameters
#### Path Parameters
- **component** (Type) - Required - The component type to create.
### Response
#### Success Response (ComponentFixture)
- **fixture** (ComponentFixture) - The created component fixture.
```
--------------------------------
### Add Tailwind CSS to Angular Project
Source: https://angular.dev/guide/tailwind
Use the Angular CLI's `ng add` command for an automated setup. This installs necessary packages and configures your project.
```bash
ng add tailwindcss
```
--------------------------------
### Toolbar Example
Source: https://angular.dev/guide/aria/api/cdk/overlay/guide/aria/toolbar
Demonstrates a toolbar with common controls. Implementing this requires careful consideration of keyboard navigation, screen reader announcements, focus management, and right-to-left language support.
```html
undo redo
format_bold format_italic format_underlined
format_align_left format_align_center format_align_right
```
--------------------------------
### Get Component Harness Instances
Source: https://angular.dev/guide/testing/using-component-harnesses
Use `getHarness()` to get the first instance of a component harness or `getAllHarnesses()` to get all instances. These methods are called on a `HarnessLoader` instance.
```typescript
// Get harness for first instance of the element
const myComponentHarness = await loader.getHarness(MyComponent);
// Get harnesses for all instances of the element
const myComponentHarnesses = await loader.getAllHarnesses(MyComponent);
```
--------------------------------
### Practical Example: Application Configuration
Source: https://angular.dev/guide/di/defining-dependency-providers
Illustrates a common use case for `useValue`: providing application configuration. This includes defining a configuration interface, creating an injection token, defining the configuration object, and providing it during application bootstrap.
```typescript
// Define configuration interface
export interface AppConfig {
apiUrl: string;
appTitle: string;
features: {
darkMode: boolean;
analytics: boolean;
};
}
// Create injection token
export const APP_CONFIG = new InjectionToken('app.config');
// Define configuration
const appConfig: AppConfig = {
apiUrl: 'https://api.example.com',
appTitle: 'My Application',
features: {
darkMode: true,
analytics: false,
},
};
// Provide in bootstrapootstrapApplication(AppComponent, {
providers: [{provide: APP_CONFIG, useValue: appConfig}],
});
// Use in component
@Component({
selector: 'app-header',
template: `
{{ title }}
`,
})
export class Header {
private config = inject(APP_CONFIG);
title = this.config.appTitle;
}
```
--------------------------------
### Configure TestBed for HTTP Client Testing
Source: https://angular.dev/guide/http/testing
Set up `TestBed` to use a testing backend for `HttpClient`. Ensure `provideHttpClient()` is listed before `provideHttpClientTesting()` to avoid potential test failures.
```typescript
TestBed.configureTestingModule({
providers: [
// ... other test providers
provideHttpClient(),
provideHttpClientTesting(),
],
});
const httpTesting = TestBed.inject(HttpTestingController);
```
--------------------------------
### Karma Test Runner Console Output Example
Source: https://angular.dev/guide/testing/karma
Example of the console output when Karma and Jasmine tests are running.
```text
02 11 2022 09:08:28.605:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/
02 11 2022 09:08:28.607:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
02 11 2022 09:08:28.620:INFO [launcher]: Starting browser Chrome
02 11 2022 09:08:31.312:INFO [Chrome]: Connected on socket -LaEYvD2R7MdcS0-AAAB with id 31534482
Chrome: Executed 3 of 3 SUCCESS (0.193 secs / 0.172 secs)
TOTAL: 3 SUCCESS
```
--------------------------------
### Tabs Overview Example
Source: https://angular.dev/guide/aria/tabs
Basic structure for Angular Aria Tabs. This example demonstrates the default tab layout.
```html
Movie
Cast
Reviews
Panel 1
```
--------------------------------
### Basic Drag and Drop List Setup
Source: https://angular.dev/guide/drag-drop
Sets up two connected lists for a drag-and-drop interface. Items can be moved between the 'Available items' and 'Shopping basket' lists.
```html
Available items
@for (item of items; track item) {
{{ item }}
}
Shopping basket
@for (item of basket; track item) {
{{ item }}
}
```
--------------------------------
### TestBed Configuration
Source: https://angular.dev/guide/testing/utility-apis
Configure the testing module with declarations, imports, and providers.
```APIDOC
## configureTestingModule
### Description
Configures the testing module with basic declaratives and service substitutes. Allows refinement by adding/removing imports, declarations, and providers.
### Method
`TestBed.configureTestingModule(metadata: TestModuleMetadata)`
### Parameters
#### Request Body
- **metadata** (TestModuleMetadata) - Required - The metadata to configure the testing module.
```typescript
type TestModuleMetadata = {
providers?: any[];
declarations?: any[];
imports?: any[];
schemas?: Array;
};
```
```
--------------------------------
### Basic Menu with Submenu Example
Source: https://angular.dev/guide/aria/menu
Demonstrates a basic menu structure with a primary menu and a nested submenu. The submenu is triggered by hovering over a menu item. Ensure cdkConnectedOverlay is imported.
```html
mark_email_readMark as read
snoozeSnooze
deleteDelete
categoryCategorizearrow_right
label_importantMark as important
starStar
labelLabel
```
--------------------------------
### Angular Component Setup with TestBed
Source: https://angular.dev/guide/testing/components-scenarios
Sets up the testing environment for an Angular component using TestBed. This includes creating component fixtures, injecting services, and querying DOM elements.
```typescript
let fixture: ComponentFixture;
let comp: Welcome;
let userAuth: UserAuthentication; // the TestBed injected service
let el: HTMLElement; // the DOM element with the welcome message
beforeEach(() => {
fixture = TestBed.createComponent(Welcome);
comp = fixture.componentInstance;
// UserAuthentication from the root injector
userAuth = TestBed.inject(UserAuthentication);
// get the "welcome" element by CSS selector (e.g., by class name)
el = fixture.nativeElement.querySelector('.welcome');
});
```
--------------------------------
### Angular Menubar Component Setup
Source: https://angular.dev/guide/aria/menubar
Sets up the main Angular component to use the Menubar and its associated Menu components. Ensure all necessary modules are imported.
```typescript
import {Component, signal, viewChild} from '@angular/core';
import {MenuBar, Menu, MenuContent, MenuItem} from '@angular/aria/menu';
import {OverlayModule} from '@angular/cdk/overlay';
@Component({
selector: 'app-root',
templateUrl: 'app.html',
styleUrl: 'app.css',
imports: [MenuBar, Menu, MenuContent, MenuItem, OverlayModule],
})
export class App {
fileMenu = viewChild