_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/examples/README.md_0_512
# API Examples This folder contains small example apps that get in-lined into our API docs. Each example contains tests for application behavior (as opposed to testing Angular's behavior) just like an Angular application developer would write. # Running the examples ``` # Serving individual examples (e.g. common) yarn bazel run //packages/examples/common:devserver # "core" examples yarn bazel run //packages/examples/core:devserver ``` # Running the tests ``` yarn bazel test //packages/examples/... ```
{ "end_byte": 512, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/README.md" }
angular/packages/examples/BUILD.bazel_0_62
exports_files([ "index.html", "tsconfig-e2e.json", ])
{ "end_byte": 62, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/BUILD.bazel" }
angular/packages/examples/test-utils/BUILD.bazel_0_316
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test-utils", srcs = ["index.ts"], deps = [ "@npm//@types/selenium-webdriver", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "end_byte": 316, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/test-utils/BUILD.bazel" }
angular/packages/examples/test-utils/index.ts_0_839
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ import {logging, WebDriver} from 'selenium-webdriver'; declare var browser: WebDriver; declare var expect: any; // TODO (juliemr): remove this method once this becomes a protractor plugin export async function verifyNoBrowserErrors() { const browserLog = await browser.manage().logs().get('browser'); const collectedErrors: any[] = []; browserLog.forEach((logEntry) => { const msg = logEntry.message; console.log('>> ' + msg, logEntry); if (logEntry.level.value >= logging.Level.INFO.value) { collectedErrors.push(msg); } }); expect(collectedErrors).toEqual([]); }
{ "end_byte": 839, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/test-utils/index.ts" }
angular/packages/examples/upgrade/upgrade_example.bzl_0_2183
load("//tools:defaults.bzl", "esbuild", "http_server", "ng_module", "protractor_web_test_suite", "ts_library") """ Macro that can be used to create the Bazel targets for an "upgrade" example. Since the upgrade examples bootstrap their application manually, and we cannot serve all examples, we need to define the devserver for each example. This macro reduces code duplication for defining these targets. """ def create_upgrade_example_targets(name, srcs, e2e_srcs, entry_point, assets = []): ng_module( name = "%s_sources" % name, srcs = srcs, deps = [ "@npm//@types/angular", "@npm//@types/jasmine", "//packages/core", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/upgrade/static", "//packages/core/testing", "//packages/upgrade/static/testing", ], tsconfig = "//packages/examples/upgrade:tsconfig-build.json", ) ts_library( name = "%s_e2e_lib" % name, srcs = e2e_srcs, testonly = True, deps = [ "@npm//@types/jasminewd2", "@npm//protractor", "//packages/examples/test-utils", "//packages/private/testing", ], tsconfig = "//packages/examples:tsconfig-e2e.json", ) esbuild( name = "app_bundle", entry_point = entry_point, deps = [":%s_sources" % name], ) http_server( name = "devserver", additional_root_paths = ["angular/packages/examples/upgrade"], srcs = [ "//packages/examples/upgrade:index.html", "//packages/zone.js/bundles:zone.umd.js", "@npm//:node_modules/angular-1.8/angular.js", "@npm//:node_modules/reflect-metadata/Reflect.js", ] + assets, deps = [":app_bundle"], ) protractor_web_test_suite( name = "%s_protractor" % name, on_prepare = "//packages/examples/upgrade:start-server.js", server = ":devserver", deps = [ ":%s_e2e_lib" % name, "@npm//selenium-webdriver", ], )
{ "end_byte": 2183, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/upgrade_example.bzl" }
angular/packages/examples/upgrade/index.html_0_632
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Angular Upgrade Examples</title> <base href="/" /> <!-- Prevent the browser from requesting any favicon. This could throw off the console output checks. --> <link rel="icon" href="data:," /> </head> <body> <example-app>Loading...</example-app> <script src="/angular/packages/zone.js/bundles/zone.umd.js"></script> <script src="/npm/node_modules/angular-1.8/angular.js"></script> <script src="/npm/node_modules/reflect-metadata/Reflect.js"></script> <script src="/app_bundle.js"></script> </body> </html>
{ "end_byte": 632, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/index.html" }
angular/packages/examples/upgrade/start-server.js_0_552
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ const protractorUtils = require('@bazel/protractor/protractor-utils'); const protractor = require('protractor'); module.exports = async function (config) { const {port} = await protractorUtils.runServer(config.workspace, config.server, '--port', []); const serverUrl = `http://localhost:${port}`; protractor.browser.baseUrl = serverUrl; };
{ "end_byte": 552, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/start-server.js" }
angular/packages/examples/upgrade/BUILD.bazel_0_142
package(default_visibility = ["//visibility:public"]) exports_files([ "tsconfig-build.json", "start-server.js", "index.html", ])
{ "end_byte": 142, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/BUILD.bazel" }
angular/packages/examples/upgrade/static/ts/full/styles.css_0_224
ng2-heroes { border: solid black 2px; display: block; padding: 5px; } ng1-hero { border: solid green 2px; margin-top: 5px; padding: 5px; display: block; } .title { background-color: blue; color: white; }
{ "end_byte": 224, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/full/styles.css" }
angular/packages/examples/upgrade/static/ts/full/module.ts_0_6766
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docplaster import { Component, Directive, ElementRef, EventEmitter, Injectable, Injector, Input, NgModule, Output, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import { downgradeComponent, downgradeInjectable, UpgradeComponent, UpgradeModule, } from '@angular/upgrade/static'; declare var angular: ng.IAngularStatic; export interface Hero { name: string; description: string; } // #docregion ng1-text-formatter-service export class TextFormatter { titleCase(value: string) { return value.replace(/((^|\s)[a-z])/g, (_, c) => c.toUpperCase()); } } // #enddocregion // #docregion ng2-heroes // This Angular component will be "downgraded" to be used in AngularJS @Component({ selector: 'ng2-heroes', // This template uses the upgraded `ng1-hero` component // Note that because its element is compiled by Angular we must use camelCased attribute names template: `<header><ng-content selector="h1"></ng-content></header> <ng-content selector=".extra"></ng-content> <div *ngFor="let hero of heroes"> <ng1-hero [hero]="hero" (onRemove)="removeHero.emit(hero)" ><strong>Super Hero</strong></ng1-hero > </div> <button (click)="addHero.emit()">Add Hero</button>`, standalone: false, }) export class Ng2HeroesComponent { @Input() heroes!: Hero[]; @Output() addHero = new EventEmitter(); @Output() removeHero = new EventEmitter(); } // #enddocregion // #docregion ng2-heroes-service // This Angular service will be "downgraded" to be used in AngularJS @Injectable() export class HeroesService { heroes: Hero[] = [ {name: 'superman', description: 'The man of steel'}, {name: 'wonder woman', description: 'Princess of the Amazons'}, {name: 'thor', description: 'The hammer-wielding god'}, ]; // #docregion use-ng1-upgraded-service constructor(textFormatter: TextFormatter) { // Change all the hero names to title case, using the "upgraded" AngularJS service this.heroes.forEach((hero: Hero) => (hero.name = textFormatter.titleCase(hero.name))); } // #enddocregion addHero() { this.heroes = this.heroes.concat([ {name: 'Kamala Khan', description: 'Epic shape-shifting healer'}, ]); } removeHero(hero: Hero) { this.heroes = this.heroes.filter((item: Hero) => item !== hero); } } // #enddocregion // #docregion ng1-hero-wrapper // This Angular directive will act as an interface to the "upgraded" AngularJS component @Directive({ selector: 'ng1-hero', standalone: false, }) export class Ng1HeroComponentWrapper extends UpgradeComponent { // The names of the input and output properties here must match the names of the // `<` and `&` bindings in the AngularJS component that is being wrapped @Input() hero!: Hero; @Output() onRemove: EventEmitter<void> = new EventEmitter(); constructor(elementRef: ElementRef, injector: Injector) { // We must pass the name of the directive as used by AngularJS to the super super('ng1Hero', elementRef, injector); } } // #enddocregion // #docregion ng2-module // This NgModule represents the Angular pieces of the application @NgModule({ declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper], providers: [ HeroesService, // #docregion upgrade-ng1-service // Register an Angular provider whose value is the "upgraded" AngularJS service {provide: TextFormatter, useFactory: (i: any) => i.get('textFormatter'), deps: ['$injector']}, // #enddocregion ], // We must import `UpgradeModule` to get access to the AngularJS core services imports: [BrowserModule, UpgradeModule], }) // #docregion bootstrap-ng1 export class Ng2AppModule { // #enddocregion ng2-module constructor(private upgrade: UpgradeModule) {} ngDoBootstrap() { // We bootstrap the AngularJS app. this.upgrade.bootstrap(document.body, [ng1AppModule.name]); } // #docregion ng2-module } // #enddocregion bootstrap-ng1 // #enddocregion ng2-module // This Angular 1 module represents the AngularJS pieces of the application export const ng1AppModule: ng.IModule = angular.module('ng1AppModule', []); // #docregion ng1-hero // This AngularJS component will be "upgraded" to be used in Angular ng1AppModule.component('ng1Hero', { bindings: {hero: '<', onRemove: '&'}, transclude: true, template: `<div class="title" ng-transclude></div> <h2>{{ $ctrl.hero.name }}</h2> <p>{{ $ctrl.hero.description }}</p> <button ng-click="$ctrl.onRemove()">Remove</button>`, }); // #enddocregion // #docregion ng1-text-formatter-service // This AngularJS service will be "upgraded" to be used in Angular ng1AppModule.service('textFormatter', [TextFormatter]); // #enddocregion // #docregion downgrade-ng2-heroes-service // Register an AngularJS service, whose value is the "downgraded" Angular injectable. ng1AppModule.factory('heroesService', downgradeInjectable(HeroesService) as any); // #enddocregion // #docregion ng2-heroes-wrapper // This directive will act as the interface to the "downgraded" Angular component ng1AppModule.directive('ng2Heroes', downgradeComponent({component: Ng2HeroesComponent})); // #enddocregion // #docregion example-app // This is our top level application component ng1AppModule.component('exampleApp', { // We inject the "downgraded" HeroesService into this AngularJS component // (We don't need the `HeroesService` type for AngularJS DI - it just helps with TypeScript // compilation) controller: [ 'heroesService', function (heroesService: HeroesService) { this.heroesService = heroesService; }, ], // This template makes use of the downgraded `ng2-heroes` component // Note that because its element is compiled by AngularJS we must use kebab-case attributes // for inputs and outputs template: `<link rel="stylesheet" href="./styles.css"> <ng2-heroes [heroes]="$ctrl.heroesService.heroes" (add-hero)="$ctrl.heroesService.addHero()" (remove-hero)="$ctrl.heroesService.removeHero($event)"> <h1>Heroes</h1> <p class="extra">There are {{ $ctrl.heroesService.heroes.length }} heroes.</p> </ng2-heroes>`, }); // #enddocregion // #docregion bootstrap-ng2 // We bootstrap the Angular module as we would do in a normal Angular app. // (We are using the dynamic browser platform as this example has not been compiled AOT.) platformBrowserDynamic().bootstrapModule(Ng2AppModule); // #enddocregion
{ "end_byte": 6766, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/full/module.ts" }
angular/packages/examples/upgrade/static/ts/full/module.spec.ts_0_1476
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion angular-setup import {TestBed} from '@angular/core/testing'; import { createAngularJSTestingModule, createAngularTestingModule, } from '@angular/upgrade/static/testing'; import {HeroesService, ng1AppModule, Ng2AppModule} from './module'; const {module, inject} = (window as any).angular.mock; // #enddocregion angular-setup describe('HeroesService (from Angular)', () => { // #docregion angular-setup beforeEach(() => { TestBed.configureTestingModule({ imports: [createAngularTestingModule([ng1AppModule.name]), Ng2AppModule], }); }); // #enddocregion angular-setup // #docregion angular-spec it('should have access to the HeroesService', () => { const heroesService = TestBed.inject(HeroesService); expect(heroesService).toBeDefined(); }); // #enddocregion angular-spec }); describe('HeroesService (from AngularJS)', () => { // #docregion angularjs-setup beforeEach(module(createAngularJSTestingModule([Ng2AppModule]))); beforeEach(module(ng1AppModule.name)); // #enddocregion angularjs-setup // #docregion angularjs-spec it('should have access to the HeroesService', inject((heroesService: HeroesService) => { expect(heroesService).toBeDefined(); })); // #enddocregion angularjs-spec });
{ "end_byte": 1476, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/full/module.spec.ts" }
angular/packages/examples/upgrade/static/ts/full/BUILD.bazel_0_476
load("//packages/examples/upgrade:upgrade_example.bzl", "create_upgrade_example_targets") package(default_visibility = ["//visibility:public"]) create_upgrade_example_targets( name = "full", srcs = glob( ["**/*.ts"], exclude = ["**/*_spec.ts"], ), assets = ["styles.css"], e2e_srcs = glob(["e2e_test/*_spec.ts"]), entry_point = ":module.ts", ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "end_byte": 476, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/full/BUILD.bazel" }
angular/packages/examples/upgrade/static/ts/full/e2e_test/static_full_spec.ts_0_1878
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; function loadPage() { browser.rootEl = 'example-app'; browser.get('/'); } describe('upgrade/static (full)', () => { beforeEach(loadPage); afterEach(verifyNoBrowserErrors); it('should render the `ng2-heroes` component', () => { expect(element(by.css('h1')).getText()).toEqual('Heroes'); expect(element.all(by.css('p')).get(0).getText()).toEqual('There are 3 heroes.'); }); it('should render 3 ng1-hero components', () => { const heroComponents = element.all(by.css('ng1-hero')); expect(heroComponents.count()).toEqual(3); }); it('should add a new hero when the "Add Hero" button is pressed', () => { const addHeroButton = element.all(by.css('button')).last(); expect(addHeroButton.getText()).toEqual('Add Hero'); addHeroButton.click(); const heroComponents = element.all(by.css('ng1-hero')); expect(heroComponents.last().element(by.css('h2')).getText()).toEqual('Kamala Khan'); }); it('should remove a hero when the "Remove" button is pressed', () => { let firstHero = element.all(by.css('ng1-hero')).get(0); expect(firstHero.element(by.css('h2')).getText()).toEqual('Superman'); const removeHeroButton = firstHero.element(by.css('button')); expect(removeHeroButton.getText()).toEqual('Remove'); removeHeroButton.click(); const heroComponents = element.all(by.css('ng1-hero')); expect(heroComponents.count()).toEqual(2); firstHero = element.all(by.css('ng1-hero')).get(0); expect(firstHero.element(by.css('h2')).getText()).toEqual('Wonder Woman'); }); });
{ "end_byte": 1878, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/full/e2e_test/static_full_spec.ts" }
angular/packages/examples/upgrade/static/ts/lite/styles.css_0_224
ng2-heroes { border: solid black 2px; display: block; padding: 5px; } ng1-hero { border: solid green 2px; margin-top: 5px; padding: 5px; display: block; } .title { background-color: blue; color: white; }
{ "end_byte": 224, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite/styles.css" }
angular/packages/examples/upgrade/static/ts/lite/module.ts_0_7635
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docplaster import { Component, Directive, ElementRef, EventEmitter, Inject, Injectable, Injector, Input, NgModule, Output, StaticProvider, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; // #docregion basic-how-to import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; // #enddocregion /* tslint:disable: no-duplicate-imports */ // #docregion basic-how-to import {downgradeComponent, downgradeModule, UpgradeComponent} from '@angular/upgrade/static'; // #enddocregion /* tslint:enable: no-duplicate-imports */ declare var angular: ng.IAngularStatic; interface Hero { name: string; description: string; } // This Angular service will use an "upgraded" AngularJS service. @Injectable() class HeroesService { heroes: Hero[] = [ {name: 'superman', description: 'The man of steel'}, {name: 'wonder woman', description: 'Princess of the Amazons'}, {name: 'thor', description: 'The hammer-wielding god'}, ]; constructor(@Inject('titleCase') titleCase: (v: string) => string) { // Change all the hero names to title case, using the "upgraded" AngularJS service. this.heroes.forEach((hero: Hero) => (hero.name = titleCase(hero.name))); } addHero() { const newHero: Hero = {name: 'Kamala Khan', description: 'Epic shape-shifting healer'}; this.heroes = this.heroes.concat([newHero]); return newHero; } removeHero(hero: Hero) { this.heroes = this.heroes.filter((item: Hero) => item !== hero); } } // This Angular component will be "downgraded" to be used in AngularJS. @Component({ selector: 'ng2-heroes', // This template uses the "upgraded" `ng1-hero` component // (Note that because its element is compiled by Angular we must use camelCased attribute names.) template: ` <div class="ng2-heroes"> <header><ng-content selector="h1"></ng-content></header> <ng-content selector=".extra"></ng-content> <div *ngFor="let hero of this.heroesService.heroes"> <ng1-hero [hero]="hero" (onRemove)="onRemoveHero(hero)"> <strong>Super Hero</strong> </ng1-hero> </div> <button (click)="onAddHero()">Add Hero</button> </div> `, standalone: false, }) class Ng2HeroesComponent { @Output() private addHero = new EventEmitter<Hero>(); @Output() private removeHero = new EventEmitter<Hero>(); constructor( @Inject('$rootScope') private $rootScope: ng.IRootScopeService, public heroesService: HeroesService, ) {} onAddHero() { const newHero = this.heroesService.addHero(); this.addHero.emit(newHero); // When a new instance of an "upgraded" component - such as `ng1Hero` - is created, we want to // run a `$digest` to initialize its bindings. Here, the component will be created by `ngFor` // asynchronously, thus we have to schedule the `$digest` to also happen asynchronously. this.$rootScope.$applyAsync(); } onRemoveHero(hero: Hero) { this.heroesService.removeHero(hero); this.removeHero.emit(hero); } } // This Angular directive will act as an interface to the "upgraded" AngularJS component. @Directive({ selector: 'ng1-hero', standalone: false, }) class Ng1HeroComponentWrapper extends UpgradeComponent { // The names of the input and output properties here must match the names of the // `<` and `&` bindings in the AngularJS component that is being wrapped. @Input() hero!: Hero; @Output() onRemove: EventEmitter<void> = new EventEmitter(); constructor(elementRef: ElementRef, injector: Injector) { // We must pass the name of the directive as used by AngularJS to the super. super('ng1Hero', elementRef, injector); } } // This Angular module represents the Angular pieces of the application. @NgModule({ imports: [BrowserModule], declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper], providers: [ HeroesService, // Register an Angular provider whose value is the "upgraded" AngularJS service. {provide: 'titleCase', useFactory: (i: any) => i.get('titleCase'), deps: ['$injector']}, ], // Note that there are no `bootstrap` components, since the "downgraded" component // will be instantiated by ngUpgrade. }) class MyLazyAngularModule { // Empty placeholder method to prevent the `Compiler` from complaining. ngDoBootstrap() {} } // #docregion basic-how-to // The function that will bootstrap the Angular module (when/if necessary). // (This would be omitted if we provided an `NgModuleFactory` directly.) const ng2BootstrapFn = (extraProviders: StaticProvider[]) => platformBrowserDynamic(extraProviders).bootstrapModule(MyLazyAngularModule); // #enddocregion // (We are using the dynamic browser platform, as this example has not been compiled AOT.) // #docregion basic-how-to // This AngularJS module represents the AngularJS pieces of the application. const myMainAngularJsModule = angular.module('myMainAngularJsModule', [ // We declare a dependency on the "downgraded" Angular module. downgradeModule(ng2BootstrapFn), // or // downgradeModule(MyLazyAngularModuleFactory) ]); // #enddocregion // This AngularJS component will be "upgraded" to be used in Angular. myMainAngularJsModule.component('ng1Hero', { bindings: {hero: '<', onRemove: '&'}, transclude: true, template: ` <div class="ng1-hero"> <div class="title" ng-transclude></div> <h2>{{ $ctrl.hero.name }}</h2> <p>{{ $ctrl.hero.description }}</p> <button ng-click="$ctrl.onRemove()">Remove</button> </div> `, }); // This AngularJS service will be "upgraded" to be used in Angular. myMainAngularJsModule.factory( 'titleCase', () => (value: string) => value.replace(/(^|\s)[a-z]/g, (m) => m.toUpperCase()), ); // This directive will act as the interface to the "downgraded" Angular component. myMainAngularJsModule.directive( 'ng2Heroes', downgradeComponent({ component: Ng2HeroesComponent, // Optionally, disable `$digest` propagation to avoid unnecessary change detection. // (Change detection is still run when the inputs of a "downgraded" component change.) propagateDigest: false, }), ); // This is our top level application component. myMainAngularJsModule.component('exampleApp', { // This template makes use of the "downgraded" `ng2-heroes` component, // but loads it lazily only when/if the user clicks the button. // (Note that because its element is compiled by AngularJS, // we must use kebab-case attributes for inputs and outputs.) template: ` <link rel="stylesheet" href="./styles.css"> <button ng-click="$ctrl.toggleHeroes()">{{ $ctrl.toggleBtnText() }}</button> <ng2-heroes ng-if="$ctrl.showHeroes" (add-hero)="$ctrl.setStatusMessage('Added hero ' + $event.name)" (remove-hero)="$ctrl.setStatusMessage('Removed hero ' + $event.name)"> <h1>Heroes</h1> <p class="extra">Status: {{ $ctrl.statusMessage }}</p> </ng2-heroes> `, controller: function () { this.showHeroes = false; this.statusMessage = 'Ready'; this.setStatusMessage = (msg: string) => (this.statusMessage = msg); this.toggleHeroes = () => (this.showHeroes = !this.showHeroes); this.toggleBtnText = () => `${this.showHeroes ? 'Hide' : 'Show'} heroes`; }, }); // We bootstrap the Angular module as we would do in a normal Angular app. angular.bootstrap(document.body, [myMainAngularJsModule.name]);
{ "end_byte": 7635, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite/module.ts" }
angular/packages/examples/upgrade/static/ts/lite/BUILD.bazel_0_469
load("//packages/examples/upgrade:upgrade_example.bzl", "create_upgrade_example_targets") package(default_visibility = ["//visibility:public"]) create_upgrade_example_targets( name = "lite", srcs = glob( ["**/*.ts"], exclude = ["e2e_test/*"], ), assets = ["styles.css"], e2e_srcs = glob(["e2e_test/*.ts"]), entry_point = ":module.ts", ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "end_byte": 469, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite/BUILD.bazel" }
angular/packages/examples/upgrade/static/ts/lite/e2e_test/static_lite_spec.ts_0_2757
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; import {addCustomMatchers} from './e2e_util'; function loadPage() { browser.rootEl = 'example-app'; browser.get('/'); } describe('upgrade/static (lite)', () => { let showHideBtn: ElementFinder; let ng2Heroes: ElementFinder; let ng2HeroesHeader: ElementFinder; let ng2HeroesExtra: ElementFinder; let ng2HeroesAddBtn: ElementFinder; let ng1Heroes: ElementArrayFinder; const expectHeroes = (isShown: boolean, ng1HeroCount = 3, statusMessage = 'Ready') => { // Verify the show/hide button text. expect(showHideBtn.getText()).toBe(isShown ? 'Hide heroes' : 'Show heroes'); // Verify the `<ng2-heroes>` component. expect(ng2Heroes.isPresent()).toBe(isShown); if (isShown) { expect(ng2HeroesHeader.getText()).toBe('Heroes'); expect(ng2HeroesExtra.getText()).toBe(`Status: ${statusMessage}`); } // Verify the `<ng1-hero>` components. expect(ng1Heroes.count()).toBe(isShown ? ng1HeroCount : 0); if (isShown) { ng1Heroes.each((ng1Hero) => expect(ng1Hero).toBeAHero()); } }; beforeEach(() => { showHideBtn = element(by.binding('toggleBtnText')); ng2Heroes = element(by.css('.ng2-heroes')); ng2HeroesHeader = ng2Heroes.element(by.css('h1')); ng2HeroesExtra = ng2Heroes.element(by.css('.extra')); ng2HeroesAddBtn = ng2Heroes.element(by.buttonText('Add Hero')); ng1Heroes = element.all(by.css('.ng1-hero')); }); beforeEach(addCustomMatchers); beforeEach(loadPage); afterEach(verifyNoBrowserErrors); it('should initially not render the heroes', () => expectHeroes(false)); it('should toggle the heroes when clicking the "show/hide" button', () => { showHideBtn.click(); expectHeroes(true); showHideBtn.click(); expectHeroes(false); }); it('should add a new hero when clicking the "add" button', () => { showHideBtn.click(); ng2HeroesAddBtn.click(); expectHeroes(true, 4, 'Added hero Kamala Khan'); expect(ng1Heroes.last()).toHaveName('Kamala Khan'); }); it('should remove a hero when clicking its "remove" button', () => { showHideBtn.click(); const firstHero = ng1Heroes.first(); expect(firstHero).toHaveName('Superman'); const removeBtn = firstHero.element(by.buttonText('Remove')); removeBtn.click(); expectHeroes(true, 2, 'Removed hero Superman'); expect(ng1Heroes.first()).not.toHaveName('Superman'); }); });
{ "end_byte": 2757, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite/e2e_test/static_lite_spec.ts" }
angular/packages/examples/upgrade/static/ts/lite/e2e_test/e2e_util.ts_0_2263
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {by, ElementFinder} from 'protractor'; declare global { namespace jasmine { interface Matchers<T> { toBeAHero(): Promise<void>; toHaveName(exectedName: string): Promise<void>; } } } const isTitleCased = (text: string) => text.split(/\s+/).every((word) => word[0] === word[0].toUpperCase()); export function addCustomMatchers() { jasmine.addMatchers({ toBeAHero: () => ({ compare(actualNg1Hero: ElementFinder | undefined) { const getText = (selector: string) => actualNg1Hero!.element(by.css(selector)).getText(); const result = { message: 'Expected undefined to be an `ng1Hero` ElementFinder.', pass: !!actualNg1Hero && Promise.all(['.title', 'h2', 'p'].map(getText) as PromiseLike<string>[]).then( ([actualTitle, actualName, actualDescription]) => { const pass = actualTitle === 'Super Hero' && isTitleCased(actualName) && actualDescription.length > 0; const actualHero = `Hero(${actualTitle}, ${actualName}, ${actualDescription})`; result.message = `Expected ${actualHero}'${pass ? ' not' : ''} to be a real hero.`; return pass; }, ), }; return result; }, }), toHaveName: () => ({ compare(actualNg1Hero: ElementFinder | undefined, expectedName: string) { const result = { message: 'Expected undefined to be an `ng1Hero` ElementFinder.', pass: !!actualNg1Hero && actualNg1Hero .element(by.css('h2')) .getText() .then((actualName) => { const pass = actualName === expectedName; result.message = `Expected Hero(${actualName})${ pass ? ' not' : '' } to have name '${expectedName}'.`; return pass; }), }; return result; }, }), } as any); }
{ "end_byte": 2263, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite/e2e_test/e2e_util.ts" }
angular/packages/examples/upgrade/static/ts/lite-multi/module.ts_0_3763
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docplaster import { Component, Directive, ElementRef, getPlatform, Injectable, Injector, NgModule, StaticProvider, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import { downgradeComponent, downgradeInjectable, downgradeModule, UpgradeComponent, } from '@angular/upgrade/static'; declare var angular: ng.IAngularStatic; // An Angular module that declares an Angular service and a component, // which in turn uses an upgraded AngularJS component. @Component({ selector: 'ng2A', template: 'Component A | <ng1A></ng1A>', standalone: false, }) export class Ng2AComponent {} @Directive({ selector: 'ng1A', standalone: false, }) export class Ng1AComponentFacade extends UpgradeComponent { constructor(elementRef: ElementRef, injector: Injector) { super('ng1A', elementRef, injector); } } @Injectable() export class Ng2AService { getValue() { return 'ng2'; } } @NgModule({ imports: [BrowserModule], providers: [Ng2AService], declarations: [Ng1AComponentFacade, Ng2AComponent], }) export class Ng2AModule { ngDoBootstrap() {} } // Another Angular module that declares an Angular component. @Component({ selector: 'ng2B', template: 'Component B', standalone: false, }) export class Ng2BComponent {} @NgModule({ imports: [BrowserModule], declarations: [Ng2BComponent], }) export class Ng2BModule { ngDoBootstrap() {} } // The downgraded Angular modules. const downgradedNg2AModule = downgradeModule((extraProviders: StaticProvider[]) => (getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(Ng2AModule), ); const downgradedNg2BModule = downgradeModule((extraProviders: StaticProvider[]) => (getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(Ng2BModule), ); // The AngularJS app including downgraded modules, components and injectables. const appModule = angular .module('exampleAppModule', [downgradedNg2AModule, downgradedNg2BModule]) .component('exampleApp', { template: ` <nav> <button ng-click="$ctrl.page = page" ng-repeat="page in ['A', 'B']"> Page {{ page }} </button> </nav> <hr /> <main ng-switch="$ctrl.page"> <ng2-a ng-switch-when="A"></ng2-a> <ng2-b ng-switch-when="B"></ng2-b> </main> `, controller: class ExampleAppController { page = 'A'; }, }) .component('ng1A', { template: 'ng1({{ $ctrl.value }})', controller: [ 'ng2AService', class Ng1AController { value: string; constructor(private ng2AService: Ng2AService) { this.value = this.ng2AService.getValue(); } }, ], }) .directive( 'ng2A', downgradeComponent({ component: Ng2AComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2AModule, propagateDigest: false, }), ) .directive( 'ng2B', downgradeComponent({ component: Ng2BComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2BModule, propagateDigest: false, }), ) .factory('ng2AService', downgradeInjectable(Ng2AService, downgradedNg2AModule)); // Bootstrap the AngularJS app. angular.bootstrap(document.body, [appModule.name]);
{ "end_byte": 3763, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite-multi/module.ts" }
angular/packages/examples/upgrade/static/ts/lite-multi/BUILD.bazel_0_453
load("//packages/examples/upgrade:upgrade_example.bzl", "create_upgrade_example_targets") package(default_visibility = ["//visibility:public"]) create_upgrade_example_targets( name = "lite-multi", srcs = glob( ["**/*.ts"], exclude = ["**/*_spec.ts"], ), e2e_srcs = glob(["e2e_test/*_spec.ts"]), entry_point = ":module.ts", ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "end_byte": 453, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite-multi/BUILD.bazel" }
angular/packages/examples/upgrade/static/ts/lite-multi/e2e_test/static_lite_multi_spec.ts_0_839
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; describe('upgrade/static (lite with multiple downgraded modules)', () => { const navButtons = element.all(by.css('nav button')); const mainContent = element(by.css('main')); beforeEach(() => browser.get('/')); afterEach(verifyNoBrowserErrors); it('should correctly bootstrap multiple downgraded modules', () => { navButtons.get(1).click(); expect(mainContent.getText()).toBe('Component B'); navButtons.get(0).click(); expect(mainContent.getText()).toBe('Component A | ng1(ng2)'); }); });
{ "end_byte": 839, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite-multi/e2e_test/static_lite_multi_spec.ts" }
angular/packages/examples/upgrade/static/ts/lite-multi-shared/module.ts_0_4809
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Compiler, Component, getPlatform, Injectable, Injector, NgModule, StaticProvider, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {downgradeComponent, downgradeModule} from '@angular/upgrade/static'; declare var angular: ng.IAngularStatic; // An Angular service provided in root. Each instance of the service will get a new ID. @Injectable({providedIn: 'root'}) export class Ng2Service { static nextId = 1; id = Ng2Service.nextId++; } // An Angular module that will act as "root" for all downgraded modules, so that injectables // provided in root will be available to all. @NgModule({ imports: [BrowserModule], }) export class Ng2RootModule { ngDoBootstrap() {} } // An Angular module that declares an Angular component, // which in turn uses an Angular service from the root module. @Component({ selector: 'ng2A', template: 'Component A (Service ID: {{ service.id }})', standalone: false, }) export class Ng2AComponent { constructor(public service: Ng2Service) {} } @NgModule({ declarations: [Ng2AComponent], }) export class Ng2AModule { ngDoBootstrap() {} } // Another Angular module that declares an Angular component, which uses the same service. @Component({ selector: 'ng2B', template: 'Component B (Service ID: {{ service.id }})', standalone: false, }) export class Ng2BComponent { constructor(public service: Ng2Service) {} } @NgModule({ declarations: [Ng2BComponent], }) export class Ng2BModule { ngDoBootstrap() {} } // A third Angular module that declares an Angular component, which uses the same service. @Component({ selector: 'ng2C', template: 'Component C (Service ID: {{ service.id }})', standalone: false, }) export class Ng2CComponent { constructor(public service: Ng2Service) {} } @NgModule({ imports: [BrowserModule], declarations: [Ng2CComponent], }) export class Ng2CModule { ngDoBootstrap() {} } // The downgraded Angular modules. Modules A and B share a common root module. Module C does not. // #docregion shared-root-module let rootInjectorPromise: Promise<Injector> | null = null; const getRootInjector = (extraProviders: StaticProvider[]) => { if (!rootInjectorPromise) { rootInjectorPromise = platformBrowserDynamic(extraProviders) .bootstrapModule(Ng2RootModule) .then((moduleRef) => moduleRef.injector); } return rootInjectorPromise; }; const downgradedNg2AModule = downgradeModule(async (extraProviders: StaticProvider[]) => { const rootInjector = await getRootInjector(extraProviders); const moduleAFactory = await rootInjector.get(Compiler).compileModuleAsync(Ng2AModule); return moduleAFactory.create(rootInjector); }); const downgradedNg2BModule = downgradeModule(async (extraProviders: StaticProvider[]) => { const rootInjector = await getRootInjector(extraProviders); const moduleBFactory = await rootInjector.get(Compiler).compileModuleAsync(Ng2BModule); return moduleBFactory.create(rootInjector); }); // #enddocregion shared-root-module const downgradedNg2CModule = downgradeModule((extraProviders: StaticProvider[]) => (getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(Ng2CModule), ); // The AngularJS app including downgraded modules and components. // #docregion shared-root-module const appModule = angular .module('exampleAppModule', [downgradedNg2AModule, downgradedNg2BModule, downgradedNg2CModule]) // #enddocregion shared-root-module .component('exampleApp', {template: '<ng2-a></ng2-a> | <ng2-b></ng2-b> | <ng2-c></ng2-c>'}) .directive( 'ng2A', downgradeComponent({ component: Ng2AComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2AModule, propagateDigest: false, }), ) .directive( 'ng2B', downgradeComponent({ component: Ng2BComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2BModule, propagateDigest: false, }), ) .directive( 'ng2C', downgradeComponent({ component: Ng2CComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2CModule, propagateDigest: false, }), ); // Bootstrap the AngularJS app. angular.bootstrap(document.body, [appModule.name]);
{ "end_byte": 4809, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite-multi-shared/module.ts" }
angular/packages/examples/upgrade/static/ts/lite-multi-shared/BUILD.bazel_0_460
load("//packages/examples/upgrade:upgrade_example.bzl", "create_upgrade_example_targets") package(default_visibility = ["//visibility:public"]) create_upgrade_example_targets( name = "lite-multi-shared", srcs = glob( ["**/*.ts"], exclude = ["**/*_spec.ts"], ), e2e_srcs = glob(["e2e_test/*_spec.ts"]), entry_point = ":module.ts", ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "end_byte": 460, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite-multi-shared/BUILD.bazel" }
angular/packages/examples/upgrade/static/ts/lite-multi-shared/e2e_test/static_lite_multi_shared_spec.ts_0_1006
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; describe('upgrade/static (lite with multiple downgraded modules and shared root module)', () => { const compA = element(by.css('ng2-a')); const compB = element(by.css('ng2-b')); const compC = element(by.css('ng2-c')); beforeEach(() => browser.get('/')); afterEach(verifyNoBrowserErrors); it('should share the same injectable instance across downgraded modules A and B', () => { expect(compA.getText()).toBe('Component A (Service ID: 2)'); expect(compB.getText()).toBe('Component B (Service ID: 2)'); }); it('should use a different injectable instance on downgraded module C', () => { expect(compC.getText()).toBe('Component C (Service ID: 1)'); }); });
{ "end_byte": 1006, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/upgrade/static/ts/lite-multi-shared/e2e_test/static_lite_multi_shared_spec.ts" }
angular/packages/examples/forms/main.ts_0_427
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import 'zone.js/lib/browser/rollup-main'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {TestsAppModule} from './test_module'; platformBrowserDynamic().bootstrapModule(TestsAppModule);
{ "end_byte": 427, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/main.ts" }
angular/packages/examples/forms/start-server.js_0_552
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ const protractorUtils = require('@bazel/protractor/protractor-utils'); const protractor = require('protractor'); module.exports = async function (config) { const {port} = await protractorUtils.runServer(config.workspace, config.server, '--port', []); const serverUrl = `http://localhost:${port}`; protractor.browser.baseUrl = serverUrl; };
{ "end_byte": 552, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/start-server.js" }
angular/packages/examples/forms/test_module.ts_0_2969
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import * as formBuilderExample from './ts/formBuilder/module'; import * as nestedFormArrayExample from './ts/nestedFormArray/module'; import * as nestedFormGroupExample from './ts/nestedFormGroup/module'; import * as ngModelGroupExample from './ts/ngModelGroup/module'; import * as radioButtonsExample from './ts/radioButtons/module'; import * as reactiveRadioButtonsExample from './ts/reactiveRadioButtons/module'; import * as reactiveSelectControlExample from './ts/reactiveSelectControl/module'; import * as selectControlExample from './ts/selectControl/module'; import * as simpleFormExample from './ts/simpleForm/module'; import * as simpleFormControlExample from './ts/simpleFormControl/module'; import * as simpleFormGroupExample from './ts/simpleFormGroup/module'; import * as simpleNgModelExample from './ts/simpleNgModel/module'; @Component({ selector: 'example-app', template: '<router-outlet></router-outlet>', standalone: false, }) export class TestsAppComponent {} @NgModule({ imports: [ formBuilderExample.AppModule, nestedFormArrayExample.AppModule, nestedFormGroupExample.AppModule, ngModelGroupExample.AppModule, radioButtonsExample.AppModule, reactiveRadioButtonsExample.AppModule, reactiveSelectControlExample.AppModule, selectControlExample.AppModule, simpleFormExample.AppModule, simpleFormControlExample.AppModule, simpleFormGroupExample.AppModule, simpleNgModelExample.AppModule, // Router configuration so that the individual e2e tests can load their // app components. RouterModule.forRoot([ {path: 'formBuilder', component: formBuilderExample.AppComponent}, {path: 'nestedFormArray', component: nestedFormArrayExample.AppComponent}, {path: 'nestedFormGroup', component: nestedFormGroupExample.AppComponent}, {path: 'ngModelGroup', component: ngModelGroupExample.AppComponent}, {path: 'radioButtons', component: radioButtonsExample.AppComponent}, {path: 'reactiveRadioButtons', component: reactiveRadioButtonsExample.AppComponent}, {path: 'reactiveSelectControl', component: reactiveSelectControlExample.AppComponent}, {path: 'selectControl', component: selectControlExample.AppComponent}, {path: 'simpleForm', component: simpleFormExample.AppComponent}, {path: 'simpleFormControl', component: simpleFormControlExample.AppComponent}, {path: 'simpleFormGroup', component: simpleFormGroupExample.AppComponent}, {path: 'simpleNgModel', component: simpleNgModelExample.AppComponent}, ]), ], declarations: [TestsAppComponent], bootstrap: [TestsAppComponent], }) export class TestsAppModule {}
{ "end_byte": 2969, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/test_module.ts" }
angular/packages/examples/forms/BUILD.bazel_0_1445
load("//tools:defaults.bzl", "esbuild", "http_server", "ng_module", "protractor_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ng_module( name = "forms_examples", srcs = glob( ["**/*.ts"], exclude = ["**/*_spec.ts"], ), deps = [ "//packages/core", "//packages/forms", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/router", "//packages/zone.js/lib", "@npm//rxjs", ], ) ts_library( name = "forms_e2e_tests_lib", testonly = True, srcs = glob(["**/e2e_test/*_spec.ts"]), tsconfig = "//packages/examples:tsconfig-e2e.json", deps = [ "//packages/examples/test-utils", "//packages/private/testing", "@npm//@types/jasminewd2", "@npm//protractor", ], ) esbuild( name = "app_bundle", entry_point = ":main.ts", deps = [":forms_examples"], ) http_server( name = "devserver", srcs = ["//packages/examples:index.html"], additional_root_paths = ["angular/packages/examples"], deps = [":app_bundle"], ) protractor_web_test_suite( name = "protractor_tests", on_prepare = ":start-server.js", server = ":devserver", deps = [ ":forms_e2e_tests_lib", "@npm//selenium-webdriver", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "end_byte": 1445, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/BUILD.bazel" }
angular/packages/examples/forms/ts/ngModelGroup/module.ts_0_600
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {NgModelGroupComp} from './ng_model_group_example'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [NgModelGroupComp], bootstrap: [NgModelGroupComp], }) export class AppModule {} export {NgModelGroupComp as AppComponent};
{ "end_byte": 600, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/ngModelGroup/module.ts" }
angular/packages/examples/forms/ts/ngModelGroup/ng_model_group_example.ts_0_1273
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ // #docregion Component import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)"> <p *ngIf="nameCtrl.invalid">Name is invalid.</p> <div ngModelGroup="name" #nameCtrl="ngModelGroup"> <input name="first" [ngModel]="name.first" minlength="2" /> <input name="middle" [ngModel]="name.middle" maxlength="2" /> <input name="last" [ngModel]="name.last" required /> </div> <input name="email" ngModel /> <button>Submit</button> </form> <button (click)="setValue()">Set value</button> `, standalone: false, }) export class NgModelGroupComp { name = {first: 'Nancy', middle: 'J', last: 'Drew'}; onSubmit(f: NgForm) { console.log(f.value); // {name: {first: 'Nancy', middle: 'J', last: 'Drew'}, email: ''} console.log(f.valid); // true } setValue() { this.name = {first: 'Bess', middle: 'S', last: 'Marvin'}; } } // #enddocregion
{ "end_byte": 1273, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/ngModelGroup/ng_model_group_example.ts" }
angular/packages/examples/forms/ts/ngModelGroup/e2e_test/ng_model_group_spec.ts_0_1419
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('ngModelGroup example', () => { afterEach(verifyNoBrowserErrors); let inputs: ElementArrayFinder; let buttons: ElementArrayFinder; beforeEach(() => { browser.get('/ngModelGroup'); inputs = element.all(by.css('input')); buttons = element.all(by.css('button')); }); it('should populate the UI with initial values', () => { expect(inputs.get(0).getAttribute('value')).toEqual('Nancy'); expect(inputs.get(1).getAttribute('value')).toEqual('J'); expect(inputs.get(2).getAttribute('value')).toEqual('Drew'); }); it('should show the error when name is invalid', () => { inputs.get(0).click(); inputs.get(0).clear(); inputs.get(0).sendKeys('a'); expect(element(by.css('p')).getText()).toEqual('Name is invalid.'); }); it('should set the value when changing the domain model', () => { buttons.get(1).click(); expect(inputs.get(0).getAttribute('value')).toEqual('Bess'); expect(inputs.get(1).getAttribute('value')).toEqual('S'); expect(inputs.get(2).getAttribute('value')).toEqual('Marvin'); }); });
{ "end_byte": 1419, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/ngModelGroup/e2e_test/ng_model_group_spec.ts" }
angular/packages/examples/forms/ts/simpleFormControl/simple_form_control_example.ts_0_778
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component} from '@angular/core'; import {FormControl, Validators} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <input [formControl]="control" /> <p>Value: {{ control.value }}</p> <p>Validation status: {{ control.status }}</p> <button (click)="setValue()">Set value</button> `, standalone: false, }) export class SimpleFormControl { control: FormControl = new FormControl('value', Validators.minLength(2)); setValue() { this.control.setValue('new value'); } } // #enddocregion
{ "end_byte": 778, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleFormControl/simple_form_control_example.ts" }
angular/packages/examples/forms/ts/simpleFormControl/module.ts_0_625
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {SimpleFormControl} from './simple_form_control_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [SimpleFormControl], bootstrap: [SimpleFormControl], }) export class AppModule {} export {SimpleFormControl as AppComponent};
{ "end_byte": 625, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleFormControl/module.ts" }
angular/packages/examples/forms/ts/simpleFormControl/e2e_test/simple_form_control_spec.ts_0_1578
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('simpleFormControl example', () => { afterEach(verifyNoBrowserErrors); describe('index view', () => { let input: ElementFinder; let valueP: ElementFinder; let statusP: ElementFinder; beforeEach(() => { browser.get('/simpleFormControl'); input = element(by.css('input')); valueP = element(by.css('p:first-of-type')); statusP = element(by.css('p:last-of-type')); }); it('should populate the form control value in the DOM', () => { expect(input.getAttribute('value')).toEqual('value'); expect(valueP.getText()).toEqual('Value: value'); }); it('should update the value as user types', () => { input.click(); input.sendKeys('s!'); expect(valueP.getText()).toEqual('Value: values!'); }); it('should show the correct validity state', () => { expect(statusP.getText()).toEqual('Validation status: VALID'); input.click(); input.clear(); input.sendKeys('a'); expect(statusP.getText()).toEqual('Validation status: INVALID'); }); it('should set the value programmatically', () => { element(by.css('button')).click(); expect(input.getAttribute('value')).toEqual('new value'); }); }); });
{ "end_byte": 1578, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleFormControl/e2e_test/simple_form_control_spec.ts" }
angular/packages/examples/forms/ts/reactiveRadioButtons/module.ts_0_651
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {ReactiveRadioButtonComp} from './reactive_radio_button_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [ReactiveRadioButtonComp], bootstrap: [ReactiveRadioButtonComp], }) export class AppModule {} export {ReactiveRadioButtonComp as AppComponent};
{ "end_byte": 651, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/reactiveRadioButtons/module.ts" }
angular/packages/examples/forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts_0_860
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Reactive import {Component} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form"> <input type="radio" formControlName="food" value="beef" /> Beef <input type="radio" formControlName="food" value="lamb" /> Lamb <input type="radio" formControlName="food" value="fish" /> Fish </form> <p>Form value: {{ form.value | json }}</p> <!-- {food: 'lamb' } --> `, standalone: false, }) export class ReactiveRadioButtonComp { form = new FormGroup({ food: new FormControl('lamb'), }); } // #enddocregion
{ "end_byte": 860, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts" }
angular/packages/examples/forms/ts/reactiveRadioButtons/e2e_test/reactive_radio_button_spec.ts_0_1305
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('radioButtons example', () => { afterEach(verifyNoBrowserErrors); let inputs: ElementArrayFinder; beforeEach(() => { browser.get('/reactiveRadioButtons'); inputs = element.all(by.css('input')); }); it('should populate the UI with initial values', () => { expect(inputs.get(0).getAttribute('checked')).toEqual(null); expect(inputs.get(1).getAttribute('checked')).toEqual('true'); expect(inputs.get(2).getAttribute('checked')).toEqual(null); expect(element(by.css('p')).getText()).toEqual('Form value: { "food": "lamb" }'); }); it('update model and other buttons as the UI value changes', () => { inputs.get(0).click(); expect(inputs.get(0).getAttribute('checked')).toEqual('true'); expect(inputs.get(1).getAttribute('checked')).toEqual(null); expect(inputs.get(2).getAttribute('checked')).toEqual(null); expect(element(by.css('p')).getText()).toEqual('Form value: { "food": "beef" }'); }); });
{ "end_byte": 1305, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/reactiveRadioButtons/e2e_test/reactive_radio_button_spec.ts" }
angular/packages/examples/forms/ts/formBuilder/module.ts_0_670
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {DisabledFormControlComponent, FormBuilderComp} from './form_builder_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [FormBuilderComp, DisabledFormControlComponent], bootstrap: [FormBuilderComp], }) export class AppModule {} export {FormBuilderComp as AppComponent};
{ "end_byte": 670, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/formBuilder/module.ts" }
angular/packages/examples/forms/ts/formBuilder/form_builder_example.ts_0_1637
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion disabled-control import {Component, Inject} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; // #enddocregion disabled-control @Component({ selector: 'example-app', template: ` <form [formGroup]="form"> <div formGroupName="name"> <input formControlName="first" placeholder="First" /> <input formControlName="last" placeholder="Last" /> </div> <input formControlName="email" placeholder="Email" /> <button>Submit</button> </form> <p>Value: {{ form.value | json }}</p> <p>Validation status: {{ form.status }}</p> `, standalone: false, }) export class FormBuilderComp { form: FormGroup; constructor(@Inject(FormBuilder) formBuilder: FormBuilder) { this.form = formBuilder.group( { name: formBuilder.group({ first: ['Nancy', Validators.minLength(2)], last: 'Drew', }), email: '', }, {updateOn: 'change'}, ); } } // #docregion disabled-control @Component({ selector: 'app-disabled-form-control', template: ` <input [formControl]="control" placeholder="First" /> `, standalone: false, }) export class DisabledFormControlComponent { control: FormControl; constructor(private formBuilder: FormBuilder) { this.control = formBuilder.control({value: 'my val', disabled: true}); } } // #enddocregion disabled-control
{ "end_byte": 1637, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/formBuilder/form_builder_example.ts" }
angular/packages/examples/forms/ts/formBuilder/e2e_test/form_builder_spec.ts_0_1136
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('formBuilder example', () => { afterEach(verifyNoBrowserErrors); let inputs: ElementArrayFinder; let paragraphs: ElementArrayFinder; beforeEach(() => { browser.get('/formBuilder'); inputs = element.all(by.css('input')); paragraphs = element.all(by.css('p')); }); it('should populate the UI with initial values', () => { expect(inputs.get(0).getAttribute('value')).toEqual('Nancy'); expect(inputs.get(1).getAttribute('value')).toEqual('Drew'); }); it('should update the validation status', () => { expect(paragraphs.get(1).getText()).toEqual('Validation status: VALID'); inputs.get(0).click(); inputs.get(0).clear(); inputs.get(0).sendKeys('a'); expect(paragraphs.get(1).getText()).toEqual('Validation status: INVALID'); }); });
{ "end_byte": 1136, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/formBuilder/e2e_test/form_builder_spec.ts" }
angular/packages/examples/forms/ts/nestedFormArray/module.ts_0_615
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {NestedFormArray} from './nested_form_array_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [NestedFormArray], bootstrap: [NestedFormArray], }) export class AppModule {} export {NestedFormArray as AppComponent};
{ "end_byte": 615, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/nestedFormArray/module.ts" }
angular/packages/examples/forms/ts/nestedFormArray/nested_form_array_example.ts_0_1336
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ // #docregion Component import {Component} from '@angular/core'; import {FormArray, FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div formArrayName="cities"> <div *ngFor="let city of cities.controls; index as i"> <input [formControlName]="i" placeholder="City" /> </div> </div> <button>Submit</button> </form> <button (click)="addCity()">Add City</button> <button (click)="setPreset()">Set preset</button> `, standalone: false, }) export class NestedFormArray { form = new FormGroup({ cities: new FormArray([new FormControl('SF'), new FormControl('NY')]), }); get cities(): FormArray { return this.form.get('cities') as FormArray; } addCity() { this.cities.push(new FormControl()); } onSubmit() { console.log(this.cities.value); // ['SF', 'NY'] console.log(this.form.value); // { cities: ['SF', 'NY'] } } setPreset() { this.cities.patchValue(['LA', 'MTV']); } } // #enddocregion
{ "end_byte": 1336, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/nestedFormArray/nested_form_array_example.ts" }
angular/packages/examples/forms/ts/nestedFormArray/e2e_test/nested_form_array_spec.ts_0_1254
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('nestedFormArray example', () => { afterEach(verifyNoBrowserErrors); let inputs: ElementArrayFinder; let buttons: ElementArrayFinder; beforeEach(() => { browser.get('/nestedFormArray'); inputs = element.all(by.css('input')); buttons = element.all(by.css('button')); }); it('should populate the UI with initial values', () => { expect(inputs.get(0).getAttribute('value')).toEqual('SF'); expect(inputs.get(1).getAttribute('value')).toEqual('NY'); }); it('should add inputs programmatically', () => { expect(inputs.count()).toBe(2); buttons.get(1).click(); inputs = element.all(by.css('input')); expect(inputs.count()).toBe(3); }); it('should set the value programmatically', () => { buttons.get(2).click(); expect(inputs.get(0).getAttribute('value')).toEqual('LA'); expect(inputs.get(1).getAttribute('value')).toEqual('MTV'); }); });
{ "end_byte": 1254, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/nestedFormArray/e2e_test/nested_form_array_spec.ts" }
angular/packages/examples/forms/ts/simpleFormGroup/module.ts_0_615
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {SimpleFormGroup} from './simple_form_group_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [SimpleFormGroup], bootstrap: [SimpleFormGroup], }) export class AppModule {} export {SimpleFormGroup as AppComponent};
{ "end_byte": 615, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleFormGroup/module.ts" }
angular/packages/examples/forms/ts/simpleFormGroup/simple_form_group_example.ts_0_1221
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ // #docregion Component import {Component} from '@angular/core'; import {FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div *ngIf="first.invalid">Name is too short.</div> <input formControlName="first" placeholder="First name" /> <input formControlName="last" placeholder="Last name" /> <button type="submit">Submit</button> </form> <button (click)="setValue()">Set preset value</button> `, standalone: false, }) export class SimpleFormGroup { form = new FormGroup({ first: new FormControl('Nancy', Validators.minLength(2)), last: new FormControl('Drew'), }); get first(): any { return this.form.get('first'); } onSubmit(): void { console.log(this.form.value); // {first: 'Nancy', last: 'Drew'} } setValue() { this.form.setValue({first: 'Carson', last: 'Drew'}); } } // #enddocregion
{ "end_byte": 1221, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleFormGroup/simple_form_group_example.ts" }
angular/packages/examples/forms/ts/simpleFormGroup/e2e_test/simple_form_group_spec.ts_0_1423
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('formControlName example', () => { afterEach(verifyNoBrowserErrors); describe('index view', () => { let firstInput: ElementFinder; let lastInput: ElementFinder; beforeEach(() => { browser.get('/simpleFormGroup'); firstInput = element(by.css('[formControlName="first"]')); lastInput = element(by.css('[formControlName="last"]')); }); it('should populate the form control values in the DOM', () => { expect(firstInput.getAttribute('value')).toEqual('Nancy'); expect(lastInput.getAttribute('value')).toEqual('Drew'); }); it('should show the error when the form is invalid', () => { firstInput.click(); firstInput.clear(); firstInput.sendKeys('a'); expect(element(by.css('div')).getText()).toEqual('Name is too short.'); }); it('should set the value programmatically', () => { element(by.css('button:not([type="submit"])')).click(); expect(firstInput.getAttribute('value')).toEqual('Carson'); expect(lastInput.getAttribute('value')).toEqual('Drew'); }); }); });
{ "end_byte": 1423, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleFormGroup/e2e_test/simple_form_group_spec.ts" }
angular/packages/examples/forms/ts/selectControl/module.ts_0_604
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {SelectControlComp} from './select_control_example'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [SelectControlComp], bootstrap: [SelectControlComp], }) export class AppModule {} export {SelectControlComp as AppComponent};
{ "end_byte": 604, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/selectControl/module.ts" }
angular/packages/examples/forms/ts/selectControl/select_control_example.ts_0_990
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <form #f="ngForm"> <select name="state" ngModel> <option value="" disabled>Choose a state</option> <option *ngFor="let state of states" [ngValue]="state"> {{ state.abbrev }} </option> </select> </form> <p>Form value: {{ f.value | json }}</p> <!-- example value: {state: {name: 'New York', abbrev: 'NY'} } --> `, standalone: false, }) export class SelectControlComp { states = [ {name: 'Arizona', abbrev: 'AZ'}, {name: 'California', abbrev: 'CA'}, {name: 'Colorado', abbrev: 'CO'}, {name: 'New York', abbrev: 'NY'}, {name: 'Pennsylvania', abbrev: 'PA'}, ]; } // #enddocregion
{ "end_byte": 990, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/selectControl/select_control_example.ts" }
angular/packages/examples/forms/ts/selectControl/e2e_test/select_control_spec.ts_0_1064
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('selectControl example', () => { afterEach(verifyNoBrowserErrors); let select: ElementFinder; let options: ElementArrayFinder; let p: ElementFinder; beforeEach(() => { browser.get('/selectControl'); select = element(by.css('select')); options = element.all(by.css('option')); p = element(by.css('p')); }); it('should initially select the placeholder option', () => { expect(options.get(0).getAttribute('selected')).toBe('true'); }); it('should update the model when the value changes in the UI', () => { select.click(); options.get(1).click(); expect(p.getText()).toEqual('Form value: { "state": { "name": "Arizona", "abbrev": "AZ" } }'); }); });
{ "end_byte": 1064, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/selectControl/e2e_test/select_control_spec.ts" }
angular/packages/examples/forms/ts/reactiveSelectControl/module.ts_0_633
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {ReactiveSelectComp} from './reactive_select_control_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [ReactiveSelectComp], bootstrap: [ReactiveSelectComp], }) export class AppModule {} export {ReactiveSelectComp as AppComponent};
{ "end_byte": 633, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/reactiveSelectControl/module.ts" }
angular/packages/examples/forms/ts/reactiveSelectControl/reactive_select_control_example.ts_0_1062
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form"> <select formControlName="state"> <option *ngFor="let state of states" [ngValue]="state"> {{ state.abbrev }} </option> </select> </form> <p>Form value: {{ form.value | json }}</p> <!-- {state: {name: 'New York', abbrev: 'NY'} } --> `, standalone: false, }) export class ReactiveSelectComp { states = [ {name: 'Arizona', abbrev: 'AZ'}, {name: 'California', abbrev: 'CA'}, {name: 'Colorado', abbrev: 'CO'}, {name: 'New York', abbrev: 'NY'}, {name: 'Pennsylvania', abbrev: 'PA'}, ]; form = new FormGroup({ state: new FormControl(this.states[3]), }); } // #enddocregion
{ "end_byte": 1062, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/reactiveSelectControl/reactive_select_control_example.ts" }
angular/packages/examples/forms/ts/reactiveSelectControl/e2e_test/reactive_select_control_spec.ts_0_1134
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('reactiveSelectControl example', () => { afterEach(verifyNoBrowserErrors); let select: ElementFinder; let options: ElementArrayFinder; let p: ElementFinder; beforeEach(() => { browser.get('/reactiveSelectControl'); select = element(by.css('select')); options = element.all(by.css('option')); p = element(by.css('p')); }); it('should populate the initial selection', () => { expect(select.getAttribute('value')).toEqual('3: Object'); expect(options.get(3).getAttribute('selected')).toBe('true'); }); it('should update the model when the value changes in the UI', () => { select.click(); options.get(0).click(); expect(p.getText()).toEqual('Form value: { "state": { "name": "Arizona", "abbrev": "AZ" } }'); }); });
{ "end_byte": 1134, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/reactiveSelectControl/e2e_test/reactive_select_control_spec.ts" }
angular/packages/examples/forms/ts/radioButtons/module.ts_0_594
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {RadioButtonComp} from './radio_button_example'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [RadioButtonComp], bootstrap: [RadioButtonComp], }) export class AppModule {} export {RadioButtonComp as AppComponent};
{ "end_byte": 594, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/radioButtons/module.ts" }
angular/packages/examples/forms/ts/radioButtons/radio_button_example.ts_0_787
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <form #f="ngForm"> <input type="radio" value="beef" name="food" [(ngModel)]="myFood" /> Beef <input type="radio" value="lamb" name="food" [(ngModel)]="myFood" /> Lamb <input type="radio" value="fish" name="food" [(ngModel)]="myFood" /> Fish </form> <p>Form value: {{ f.value | json }}</p> <!-- {food: 'lamb' } --> <p>myFood value: {{ myFood }}</p> <!-- 'lamb' --> `, standalone: false, }) export class RadioButtonComp { myFood = 'lamb'; }
{ "end_byte": 787, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/radioButtons/radio_button_example.ts" }
angular/packages/examples/forms/ts/radioButtons/e2e_test/radio_button_spec.ts_0_1514
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('radioButtons example', () => { afterEach(verifyNoBrowserErrors); let inputs: ElementArrayFinder; let paragraphs: ElementArrayFinder; beforeEach(() => { browser.get('/radioButtons'); inputs = element.all(by.css('input')); paragraphs = element.all(by.css('p')); }); it('should populate the UI with initial values', () => { expect(inputs.get(0).getAttribute('checked')).toEqual(null); expect(inputs.get(1).getAttribute('checked')).toEqual('true'); expect(inputs.get(2).getAttribute('checked')).toEqual(null); expect(paragraphs.get(0).getText()).toEqual('Form value: { "food": "lamb" }'); expect(paragraphs.get(1).getText()).toEqual('myFood value: lamb'); }); it('update model and other buttons as the UI value changes', () => { inputs.get(0).click(); expect(inputs.get(0).getAttribute('checked')).toEqual('true'); expect(inputs.get(1).getAttribute('checked')).toEqual(null); expect(inputs.get(2).getAttribute('checked')).toEqual(null); expect(paragraphs.get(0).getText()).toEqual('Form value: { "food": "beef" }'); expect(paragraphs.get(1).getText()).toEqual('myFood value: beef'); }); });
{ "end_byte": 1514, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/radioButtons/e2e_test/radio_button_spec.ts" }
angular/packages/examples/forms/ts/simpleNgModel/module.ts_0_605
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {SimpleNgModelComp} from './simple_ng_model_example'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [SimpleNgModelComp], bootstrap: [SimpleNgModelComp], }) export class AppModule {} export {SimpleNgModelComp as AppComponent};
{ "end_byte": 605, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleNgModel/module.ts" }
angular/packages/examples/forms/ts/simpleNgModel/simple_ng_model_example.ts_0_647
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <input [(ngModel)]="name" #ctrl="ngModel" required /> <p>Value: {{ name }}</p> <p>Valid: {{ ctrl.valid }}</p> <button (click)="setValue()">Set value</button> `, standalone: false, }) export class SimpleNgModelComp { name: string = ''; setValue() { this.name = 'Nancy'; } } // #enddocregion
{ "end_byte": 647, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleNgModel/simple_ng_model_example.ts" }
angular/packages/examples/forms/ts/simpleNgModel/e2e_test/simple_ng_model_spec.ts_0_1280
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('simpleNgModel example', () => { afterEach(verifyNoBrowserErrors); let input: ElementFinder; let paragraphs: ElementArrayFinder; let button: ElementFinder; beforeEach(() => { browser.get('/simpleNgModel'); input = element(by.css('input')); paragraphs = element.all(by.css('p')); button = element(by.css('button')); }); it('should update the domain model as you type', () => { input.click(); input.sendKeys('Carson'); expect(paragraphs.get(0).getText()).toEqual('Value: Carson'); }); it('should report the validity correctly', () => { expect(paragraphs.get(1).getText()).toEqual('Valid: false'); input.click(); input.sendKeys('a'); expect(paragraphs.get(1).getText()).toEqual('Valid: true'); }); it('should set the value by changing the domain model', () => { button.click(); expect(input.getAttribute('value')).toEqual('Nancy'); }); });
{ "end_byte": 1280, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleNgModel/e2e_test/simple_ng_model_spec.ts" }
angular/packages/examples/forms/ts/simpleForm/module.ts_0_589
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {SimpleFormComp} from './simple_form_example'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [SimpleFormComp], bootstrap: [SimpleFormComp], }) export class AppModule {} export {SimpleFormComp as AppComponent};
{ "end_byte": 589, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleForm/module.ts" }
angular/packages/examples/forms/ts/simpleForm/simple_form_example.ts_0_966
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ // #docregion Component import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate> <input name="first" ngModel required #first="ngModel" /> <input name="last" ngModel /> <button>Submit</button> </form> <p>First name value: {{ first.value }}</p> <p>First name valid: {{ first.valid }}</p> <p>Form value: {{ f.value | json }}</p> <p>Form valid: {{ f.valid }}</p> `, standalone: false, }) export class SimpleFormComp { onSubmit(f: NgForm) { console.log(f.value); // { first: '', last: '' } console.log(f.valid); // false } } // #enddocregion
{ "end_byte": 966, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleForm/simple_form_example.ts" }
angular/packages/examples/forms/ts/simpleForm/e2e_test/simple_form_spec.ts_0_1417
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('simpleForm example', () => { afterEach(verifyNoBrowserErrors); let inputs: ElementArrayFinder; let paragraphs: ElementArrayFinder; beforeEach(() => { browser.get('/simpleForm'); inputs = element.all(by.css('input')); paragraphs = element.all(by.css('p')); }); it('should update the domain model as you type', () => { inputs.get(0).click(); inputs.get(0).sendKeys('Nancy'); inputs.get(1).click(); inputs.get(1).sendKeys('Drew'); expect(paragraphs.get(0).getText()).toEqual('First name value: Nancy'); expect(paragraphs.get(2).getText()).toEqual('Form value: { "first": "Nancy", "last": "Drew" }'); }); it('should report the validity correctly', () => { expect(paragraphs.get(1).getText()).toEqual('First name valid: false'); expect(paragraphs.get(3).getText()).toEqual('Form valid: false'); inputs.get(0).click(); inputs.get(0).sendKeys('a'); expect(paragraphs.get(1).getText()).toEqual('First name valid: true'); expect(paragraphs.get(3).getText()).toEqual('Form valid: true'); }); });
{ "end_byte": 1417, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/simpleForm/e2e_test/simple_form_spec.ts" }
angular/packages/examples/forms/ts/nestedFormGroup/module.ts_0_631
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {NestedFormGroupComp} from './nested_form_group_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [NestedFormGroupComp], bootstrap: [NestedFormGroupComp], }) export class AppModule {} export {NestedFormGroupComp as AppComponent};
{ "end_byte": 631, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/nestedFormGroup/module.ts" }
angular/packages/examples/forms/ts/nestedFormGroup/nested_form_group_example.ts_0_1647
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ // #docregion Component import {Component} from '@angular/core'; import {FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <p *ngIf="name.invalid">Name is invalid.</p> <div formGroupName="name"> <input formControlName="first" placeholder="First name" /> <input formControlName="last" placeholder="Last name" /> </div> <input formControlName="email" placeholder="Email" /> <button type="submit">Submit</button> </form> <button (click)="setPreset()">Set preset</button> `, standalone: false, }) export class NestedFormGroupComp { form = new FormGroup({ name: new FormGroup({ first: new FormControl('Nancy', Validators.minLength(2)), last: new FormControl('Drew', Validators.required), }), email: new FormControl(), }); get first(): any { return this.form.get('name.first'); } get name(): any { return this.form.get('name'); } onSubmit() { console.log(this.first.value); // 'Nancy' console.log(this.name.value); // {first: 'Nancy', last: 'Drew'} console.log(this.form.value); // {name: {first: 'Nancy', last: 'Drew'}, email: ''} console.log(this.form.status); // VALID } setPreset() { this.name.setValue({first: 'Bess', last: 'Marvin'}); } } // #enddocregion
{ "end_byte": 1647, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/nestedFormGroup/nested_form_group_example.ts" }
angular/packages/examples/forms/ts/nestedFormGroup/e2e_test/nested_form_group_spec.ts_0_1373
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../test-utils'; describe('nestedFormGroup example', () => { afterEach(verifyNoBrowserErrors); let firstInput: ElementFinder; let lastInput: ElementFinder; let button: ElementFinder; beforeEach(() => { browser.get('/nestedFormGroup'); firstInput = element(by.css('[formControlName="first"]')); lastInput = element(by.css('[formControlName="last"]')); button = element(by.css('button:not([type="submit"])')); }); it('should populate the UI with initial values', () => { expect(firstInput.getAttribute('value')).toEqual('Nancy'); expect(lastInput.getAttribute('value')).toEqual('Drew'); }); it('should show the error when name is invalid', () => { firstInput.click(); firstInput.clear(); firstInput.sendKeys('a'); expect(element(by.css('p')).getText()).toEqual('Name is invalid.'); }); it('should set the value programmatically', () => { button.click(); expect(firstInput.getAttribute('value')).toEqual('Bess'); expect(lastInput.getAttribute('value')).toEqual('Marvin'); }); });
{ "end_byte": 1373, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/forms/ts/nestedFormGroup/e2e_test/nested_form_group_spec.ts" }
angular/packages/examples/core/main.ts_0_481
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import 'zone.js/lib/browser/rollup-main'; import 'zone.js/lib/zone-spec/task-tracking'; // okd import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {TestsAppModule} from './test_module'; platformBrowserDynamic().bootstrapModule(TestsAppModule);
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/main.ts" }
angular/packages/examples/core/start-server.js_0_552
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ const protractorUtils = require('@bazel/protractor/protractor-utils'); const protractor = require('protractor'); module.exports = async function (config) { const {port} = await protractorUtils.runServer(config.workspace, config.server, '--port', []); const serverUrl = `http://localhost:${port}`; protractor.browser.baseUrl = serverUrl; };
{ "end_byte": 552, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/start-server.js" }
angular/packages/examples/core/test_module.ts_0_1866
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import * as animationDslExample from './animation/ts/dsl/module'; import * as diContentChildExample from './di/ts/contentChild/module'; import * as diContentChildrenExample from './di/ts/contentChildren/module'; import * as diViewChildExample from './di/ts/viewChild/module'; import * as diViewChildrenExample from './di/ts/viewChildren/module'; import * as testabilityWhenStableExample from './testability/ts/whenStable/module'; @Component({ selector: 'example-app', template: '<router-outlet></router-outlet>', standalone: false, }) export class TestsAppComponent {} @NgModule({ imports: [ animationDslExample.AppModule, diContentChildExample.AppModule, diContentChildrenExample.AppModule, diViewChildExample.AppModule, diViewChildrenExample.AppModule, testabilityWhenStableExample.AppModule, // Router configuration so that the individual e2e tests can load their // app components. RouterModule.forRoot([ {path: 'animation/dsl', component: animationDslExample.AppComponent}, {path: 'di/contentChild', component: diContentChildExample.AppComponent}, {path: 'di/contentChildren', component: diContentChildrenExample.AppComponent}, {path: 'di/viewChild', component: diViewChildExample.AppComponent}, {path: 'di/viewChildren', component: diViewChildrenExample.AppComponent}, {path: 'testability/whenStable', component: testabilityWhenStableExample.AppComponent}, ]), ], declarations: [TestsAppComponent], bootstrap: [TestsAppComponent], }) export class TestsAppModule {}
{ "end_byte": 1866, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/test_module.ts" }
angular/packages/examples/core/BUILD.bazel_0_1999
load("//tools:defaults.bzl", "esbuild", "http_server", "jasmine_node_test", "ng_module", "protractor_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ng_module( name = "core_examples", srcs = glob( ["**/*.ts"], exclude = [ "**/*_spec.ts", "**/*_howto.ts", ], ), deps = [ "//packages/animations", "//packages/core", "//packages/forms", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/animations", "//packages/router", "//packages/zone.js/lib", "@npm//rxjs", ], ) ts_library( name = "core_tests_lib", testonly = True, srcs = glob( ["**/*_spec.ts"], exclude = ["**/e2e_test/*"], ), deps = [ "//packages/core", "//packages/core/testing", ], ) ts_library( name = "core_e2e_tests_lib", testonly = True, srcs = glob(["**/e2e_test/*_spec.ts"]), tsconfig = "//packages/examples:tsconfig-e2e.json", deps = [ "//packages/examples/test-utils", "@npm//@types/jasminewd2", "@npm//protractor", ], ) esbuild( name = "app_bundle", entry_point = ":main.ts", deps = [":core_examples"], ) http_server( name = "devserver", srcs = ["//packages/examples:index.html"], additional_root_paths = ["angular/packages/examples"], deps = [":app_bundle"], ) protractor_web_test_suite( name = "protractor_tests", on_prepare = ":start-server.js", server = ":devserver", deps = [ ":core_e2e_tests_lib", "@npm//selenium-webdriver", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":core_tests_lib", "//packages/examples/core/di/ts/forward_ref:forward_ref_tests_lib", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "end_byte": 1999, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/BUILD.bazel" }
angular/packages/examples/core/di/ts/metadata_spec.ts_0_5289
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Component, Directive, Host, Injectable, Injector, Optional, Self, SkipSelf, } from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; { describe('di metadata examples', () => { describe('Inject', () => { it('works without decorator', () => { // #docregion InjectWithoutDecorator class Engine {} @Injectable() class Car { constructor(public engine: Engine) {} // same as constructor(@Inject(Engine) engine:Engine) } const injector = Injector.create({ providers: [ {provide: Engine, deps: []}, {provide: Car, deps: [Engine]}, ], }); expect(injector.get(Car).engine instanceof Engine).toBe(true); // #enddocregion }); }); describe('Optional', () => { it('works', () => { // #docregion Optional class Engine {} @Injectable() class Car { constructor(@Optional() public engine: Engine) {} } const injector = Injector.create({ providers: [{provide: Car, deps: [[new Optional(), Engine]]}], }); expect(injector.get(Car).engine).toBeNull(); // #enddocregion }); }); describe('Injectable', () => { it('works', () => { // #docregion Injectable @Injectable() class UsefulService {} @Injectable() class NeedsService { constructor(public service: UsefulService) {} } const injector = Injector.create({ providers: [ {provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}, ], }); expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true); // #enddocregion }); }); describe('Self', () => { it('works', () => { // #docregion Self class Dependency {} @Injectable() class NeedsDependency { constructor(@Self() public dependency: Dependency) {} } let inj = Injector.create({ providers: [ {provide: Dependency, deps: []}, {provide: NeedsDependency, deps: [[new Self(), Dependency]]}, ], }); const nd = inj.get(NeedsDependency); expect(nd.dependency instanceof Dependency).toBe(true); const child = Injector.create({ providers: [{provide: NeedsDependency, deps: [[new Self(), Dependency]]}], parent: inj, }); expect(() => child.get(NeedsDependency)).toThrowError(); // #enddocregion }); }); describe('SkipSelf', () => { it('works', () => { // #docregion SkipSelf class Dependency {} @Injectable() class NeedsDependency { constructor(@SkipSelf() public dependency: Dependency) {} } const parent = Injector.create({providers: [{provide: Dependency, deps: []}]}); const child = Injector.create({ providers: [{provide: NeedsDependency, deps: [Dependency]}], parent, }); expect(child.get(NeedsDependency).dependency instanceof Dependency).toBe(true); const inj = Injector.create({ providers: [{provide: NeedsDependency, deps: [[new Self(), Dependency]]}], }); expect(() => inj.get(NeedsDependency)).toThrowError(); // #enddocregion }); }); describe('Host', () => { it('works', () => { // #docregion Host class OtherService {} class HostService {} @Directive({ selector: 'child-directive', standalone: false, }) class ChildDirective { logs: string[] = []; constructor(@Optional() @Host() os: OtherService, @Optional() @Host() hs: HostService) { // os is null: true this.logs.push(`os is null: ${os === null}`); // hs is an instance of HostService: true this.logs.push(`hs is an instance of HostService: ${hs instanceof HostService}`); } } @Component({ selector: 'parent-cmp', viewProviders: [HostService], template: '<child-directive></child-directive>', standalone: false, }) class ParentCmp {} @Component({ selector: 'app', viewProviders: [OtherService], template: '<parent-cmp></parent-cmp>', standalone: false, }) class App {} // #enddocregion TestBed.configureTestingModule({ declarations: [App, ParentCmp, ChildDirective], }); let cmp: ComponentFixture<App> = undefined!; expect(() => (cmp = TestBed.createComponent(App))).not.toThrow(); expect(cmp.debugElement.children[0].children[0].injector.get(ChildDirective).logs).toEqual([ 'os is null: true', 'hs is an instance of HostService: true', ]); }); }); }); }
{ "end_byte": 5289, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/metadata_spec.ts" }
angular/packages/examples/core/di/ts/injector_spec.ts_0_3068
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { inject, InjectFlags, InjectionToken, InjectOptions, Injector, ProviderToken, ɵInjectorProfilerContext, ɵsetCurrentInjector as setCurrentInjector, ɵsetInjectorProfilerContext, } from '@angular/core'; class MockRootScopeInjector implements Injector { constructor(readonly parent: Injector) {} get<T>( token: ProviderToken<T>, defaultValue?: any, flags: InjectFlags | InjectOptions = InjectFlags.Default, ): T { if ((token as any).ɵprov && (token as any).ɵprov.providedIn === 'root') { const old = setCurrentInjector(this); const previousInjectorProfilerContext = ɵsetInjectorProfilerContext({ injector: this, token: null, }); try { return (token as any).ɵprov.factory(); } finally { setCurrentInjector(old); ɵsetInjectorProfilerContext(previousInjectorProfilerContext); } } return this.parent.get(token, defaultValue, flags); } } { describe('injector metadata examples', () => { it('works', () => { // #docregion Injector const injector: Injector = Injector.create({ providers: [{provide: 'validToken', useValue: 'Value'}], }); expect(injector.get('validToken')).toEqual('Value'); expect(() => injector.get('invalidToken')).toThrowError(); expect(injector.get('invalidToken', 'notFound')).toEqual('notFound'); // #enddocregion }); it('injects injector', () => { // #docregion injectInjector const injector = Injector.create({providers: []}); expect(injector.get(Injector)).toBe(injector); // #enddocregion }); it('should infer type', () => { // #docregion InjectionToken const BASE_URL = new InjectionToken<string>('BaseUrl'); const injector = Injector.create({ providers: [{provide: BASE_URL, useValue: 'http://localhost'}], }); const url = injector.get(BASE_URL); // Note: since `BASE_URL` is `InjectionToken<string>` // `url` is correctly inferred to be `string` expect(url).toBe('http://localhost'); // #enddocregion }); it('injects a tree-shakeable InjectionToken', () => { class MyDep {} const injector = new MockRootScopeInjector( Injector.create({providers: [{provide: MyDep, deps: []}]}), ); // #docregion ShakableInjectionToken class MyService { constructor(readonly myDep: MyDep) {} } const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', { providedIn: 'root', factory: () => new MyService(inject(MyDep)), }); const instance = injector.get(MY_SERVICE_TOKEN); expect(instance instanceof MyService).toBeTruthy(); expect(instance.myDep instanceof MyDep).toBeTruthy(); // #enddocregion }); }); }
{ "end_byte": 3068, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/injector_spec.ts" }
angular/packages/examples/core/di/ts/provider_spec.ts_0_6666
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injectable, InjectionToken, Injector, Optional} from '@angular/core'; { describe('Provider examples', () => { describe('TypeProvider', () => { it('works', () => { // #docregion TypeProvider @Injectable() class Greeting { salutation = 'Hello'; } const injector = Injector.create({providers: [{provide: Greeting, useClass: Greeting}]}); expect(injector.get(Greeting).salutation).toBe('Hello'); // #enddocregion }); }); describe('ValueProvider', () => { it('works', () => { // #docregion ValueProvider const injector = Injector.create({providers: [{provide: String, useValue: 'Hello'}]}); expect(injector.get(String)).toEqual('Hello'); // #enddocregion }); }); describe('MultiProviderAspect', () => { it('works', () => { // #docregion MultiProviderAspect const locale = new InjectionToken<string[]>('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ], }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']); // #enddocregion }); }); describe('ClassProvider', () => { it('works', () => { // #docregion ClassProvider abstract class Shape { name!: string; } class Square extends Shape { override name = 'square'; } const injector = Injector.create({providers: [{provide: Shape, useValue: new Square()}]}); const shape: Shape = injector.get(Shape); expect(shape.name).toEqual('square'); expect(shape instanceof Square).toBe(true); // #enddocregion }); it('is different then useExisting', () => { // #docregion ClassProviderDifference class Greeting { salutation = 'Hello'; } class FormalGreeting extends Greeting { override salutation = 'Greetings'; } const injector = Injector.create({ providers: [ {provide: FormalGreeting, useClass: FormalGreeting}, {provide: Greeting, useClass: FormalGreeting}, ], }); // The injector returns different instances. // See: {provide: ?, useExisting: ?} if you want the same instance. expect(injector.get(FormalGreeting)).not.toBe(injector.get(Greeting)); // #enddocregion }); }); describe('StaticClassProvider', () => { it('works', () => { // #docregion StaticClassProvider abstract class Shape { name!: string; } class Square extends Shape { override name = 'square'; } const injector = Injector.create({ providers: [{provide: Shape, useClass: Square, deps: []}], }); const shape: Shape = injector.get(Shape); expect(shape.name).toEqual('square'); expect(shape instanceof Square).toBe(true); // #enddocregion }); it('is different then useExisting', () => { // #docregion StaticClassProviderDifference class Greeting { salutation = 'Hello'; } class FormalGreeting extends Greeting { override salutation = 'Greetings'; } const injector = Injector.create({ providers: [ {provide: FormalGreeting, useClass: FormalGreeting, deps: []}, {provide: Greeting, useClass: FormalGreeting, deps: []}, ], }); // The injector returns different instances. // See: {provide: ?, useExisting: ?} if you want the same instance. expect(injector.get(FormalGreeting)).not.toBe(injector.get(Greeting)); // #enddocregion }); }); describe('ConstructorProvider', () => { it('works', () => { // #docregion ConstructorProvider class Square { name = 'square'; } const injector = Injector.create({providers: [{provide: Square, deps: []}]}); const shape: Square = injector.get(Square); expect(shape.name).toEqual('square'); expect(shape instanceof Square).toBe(true); // #enddocregion }); }); describe('ExistingProvider', () => { it('works', () => { // #docregion ExistingProvider class Greeting { salutation = 'Hello'; } class FormalGreeting extends Greeting { override salutation = 'Greetings'; } const injector = Injector.create({ providers: [ {provide: FormalGreeting, deps: []}, {provide: Greeting, useExisting: FormalGreeting}, ], }); expect(injector.get(Greeting).salutation).toEqual('Greetings'); expect(injector.get(FormalGreeting).salutation).toEqual('Greetings'); expect(injector.get(FormalGreeting)).toBe(injector.get(Greeting)); // #enddocregion }); }); describe('FactoryProvider', () => { it('works', () => { // #docregion FactoryProvider const Location = new InjectionToken('location'); const Hash = new InjectionToken('hash'); const injector = Injector.create({ providers: [ {provide: Location, useValue: 'https://angular.io/#someLocation'}, { provide: Hash, useFactory: (location: string) => location.split('#')[1], deps: [Location], }, ], }); expect(injector.get(Hash)).toEqual('someLocation'); // #enddocregion }); it('supports optional dependencies', () => { // #docregion FactoryProviderOptionalDeps const Location = new InjectionToken('location'); const Hash = new InjectionToken('hash'); const injector = Injector.create({ providers: [ { provide: Hash, useFactory: (location: string) => `Hash for: ${location}`, // use a nested array to define metadata for dependencies. deps: [[new Optional(), Location]], }, ], }); expect(injector.get(Hash)).toEqual('Hash for: null'); // #enddocregion }); }); }); }
{ "end_byte": 6666, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/provider_spec.ts" }
angular/packages/examples/core/di/ts/forward_ref/BUILD.bazel_0_859
load("//tools:defaults.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) # Note: The `forward_ref` example tests are built through this `ng_module` sub-target. # This is done so that DI decorator/type metadata is processed manually by the compiler # ahead of time. We cannot rely on the official TypeScript decorator downlevel emit (for JIT), # as the output is not compatible with `forwardRef` and ES2015+. More details here: # https://github.com/angular/angular/commit/323651bd38909b0f4226bcb6c8f5abafa91cf9d9. # https://github.com/microsoft/TypeScript/issues/27519. ng_module( name = "forward_ref_tests_lib", testonly = True, srcs = ["forward_ref_spec.ts"], visibility = ["//packages/examples/core:__pkg__"], deps = ["//packages/core"], ) filegroup( name = "files_for_docgen", srcs = glob(["*.ts"]), )
{ "end_byte": 859, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/forward_ref/BUILD.bazel" }
angular/packages/examples/core/di/ts/forward_ref/forward_ref_spec.ts_0_1621
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {forwardRef, Inject, Injectable, Injector, resolveForwardRef} from '@angular/core'; { describe('forwardRef examples', () => { it('ForwardRefFn example works', () => { // #docregion forward_ref_fn const ref = forwardRef(() => Lock); // #enddocregion expect(ref).not.toBeNull(); class Lock {} }); it('can be used to inject a class defined later', () => { // #docregion forward_ref @Injectable() class Door { lock: Lock; // Door attempts to inject Lock, despite it not being defined yet. // forwardRef makes this possible. constructor(@Inject(forwardRef(() => Lock)) lock: Lock) { this.lock = lock; } } // Only at this point Lock is defined. class Lock {} const injector = Injector.create({ providers: [ {provide: Lock, deps: []}, {provide: Door, deps: [Lock]}, ], }); expect(injector.get(Door) instanceof Door).toBe(true); expect(injector.get(Door).lock instanceof Lock).toBe(true); // #enddocregion }); it('can be unwrapped', () => { // #docregion resolve_forward_ref const ref = forwardRef(() => 'refValue'); expect(resolveForwardRef(ref as any)).toEqual('refValue'); expect(resolveForwardRef('regularValue')).toEqual('regularValue'); // #enddocregion }); }); }
{ "end_byte": 1621, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/forward_ref/forward_ref_spec.ts" }
angular/packages/examples/core/di/ts/contentChild/content_child_howto.ts_0_634
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion HowTo import {AfterContentInit, ContentChild, Directive} from '@angular/core'; @Directive({ selector: 'child-directive', standalone: false, }) class ChildDirective {} @Directive({ selector: 'someDir', standalone: false, }) class SomeDir implements AfterContentInit { @ContentChild(ChildDirective) contentChild!: ChildDirective; ngAfterContentInit() { // contentChild is set } } // #enddocregion
{ "end_byte": 634, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/contentChild/content_child_howto.ts" }
angular/packages/examples/core/di/ts/contentChild/module.ts_0_564
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {ContentChildComp, Pane, Tab} from './content_child_example'; @NgModule({ imports: [BrowserModule], declarations: [ContentChildComp, Pane, Tab], bootstrap: [ContentChildComp], }) export class AppModule {} export {ContentChildComp as AppComponent};
{ "end_byte": 564, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/contentChild/module.ts" }
angular/packages/examples/core/di/ts/contentChild/content_child_example.ts_0_943
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component, ContentChild, Directive, Input} from '@angular/core'; @Directive({ selector: 'pane', standalone: false, }) export class Pane { @Input() id!: string; } @Component({ selector: 'tab', template: ` <div>pane: {{ pane?.id }}</div> `, standalone: false, }) export class Tab { @ContentChild(Pane) pane!: Pane; } @Component({ selector: 'example-app', template: ` <tab> <pane id="1" *ngIf="shouldShow"></pane> <pane id="2" *ngIf="!shouldShow"></pane> </tab> <button (click)="toggle()">Toggle</button> `, standalone: false, }) export class ContentChildComp { shouldShow = true; toggle() { this.shouldShow = !this.shouldShow; } } // #enddocregion
{ "end_byte": 943, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/contentChild/content_child_example.ts" }
angular/packages/examples/core/di/ts/contentChild/e2e_test/content_child_spec.ts_0_786
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; describe('contentChild example', () => { afterEach(verifyNoBrowserErrors); let button: ElementFinder; let result: ElementFinder; beforeEach(() => { browser.get('/di/contentChild'); button = element(by.css('button')); result = element(by.css('div')); }); it('should query content child', () => { expect(result.getText()).toEqual('pane: 1'); button.click(); expect(result.getText()).toEqual('pane: 2'); }); });
{ "end_byte": 786, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/contentChild/e2e_test/content_child_spec.ts" }
angular/packages/examples/core/di/ts/viewChild/module.ts_0_540
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {Pane, ViewChildComp} from './view_child_example'; @NgModule({ imports: [BrowserModule], declarations: [ViewChildComp, Pane], bootstrap: [ViewChildComp], }) export class AppModule {} export {ViewChildComp as AppComponent};
{ "end_byte": 540, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/viewChild/module.ts" }
angular/packages/examples/core/di/ts/viewChild/view_child_example.ts_0_934
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component, Directive, Input, ViewChild} from '@angular/core'; @Directive({ selector: 'pane', standalone: false, }) export class Pane { @Input() id!: string; } @Component({ selector: 'example-app', template: ` <pane id="1" *ngIf="shouldShow"></pane> <pane id="2" *ngIf="!shouldShow"></pane> <button (click)="toggle()">Toggle</button> <div>Selected: {{ selectedPane }}</div> `, standalone: false, }) export class ViewChildComp { @ViewChild(Pane) set pane(v: Pane) { setTimeout(() => { this.selectedPane = v.id; }, 0); } selectedPane: string = ''; shouldShow = true; toggle() { this.shouldShow = !this.shouldShow; } } // #enddocregion
{ "end_byte": 934, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/viewChild/view_child_example.ts" }
angular/packages/examples/core/di/ts/viewChild/view_child_howto.ts_0_647
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion HowTo import {AfterViewInit, Component, Directive, ViewChild} from '@angular/core'; @Directive({ selector: 'child-directive', standalone: false, }) class ChildDirective {} @Component({ selector: 'someCmp', templateUrl: 'someCmp.html', standalone: false, }) class SomeCmp implements AfterViewInit { @ViewChild(ChildDirective) child!: ChildDirective; ngAfterViewInit() { // child is set } } // #enddocregion
{ "end_byte": 647, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/viewChild/view_child_howto.ts" }
angular/packages/examples/core/di/ts/viewChild/e2e_test/view_child_spec.ts_0_785
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; describe('viewChild example', () => { afterEach(verifyNoBrowserErrors); let button: ElementFinder; let result: ElementFinder; beforeEach(() => { browser.get('/di/viewChild'); button = element(by.css('button')); result = element(by.css('div')); }); it('should query view child', () => { expect(result.getText()).toEqual('Selected: 1'); button.click(); expect(result.getText()).toEqual('Selected: 2'); }); });
{ "end_byte": 785, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/viewChild/e2e_test/view_child_spec.ts" }
angular/packages/examples/core/di/ts/contentChildren/module.ts_0_579
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {ContentChildrenComp, Pane, Tab} from './content_children_example'; @NgModule({ imports: [BrowserModule], declarations: [ContentChildrenComp, Pane, Tab], bootstrap: [ContentChildrenComp], }) export class AppModule {} export {ContentChildrenComp as AppComponent};
{ "end_byte": 579, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/contentChildren/module.ts" }
angular/packages/examples/core/di/ts/contentChildren/content_children_example.ts_0_1554
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component, ContentChildren, Directive, Input, QueryList} from '@angular/core'; @Directive({ selector: 'pane', standalone: false, }) export class Pane { @Input() id!: string; } @Component({ selector: 'tab', template: ` <div class="top-level">Top level panes: {{ serializedPanes }}</div> <div class="nested">Arbitrary nested panes: {{ serializedNestedPanes }}</div> `, standalone: false, }) export class Tab { @ContentChildren(Pane) topLevelPanes!: QueryList<Pane>; @ContentChildren(Pane, {descendants: true}) arbitraryNestedPanes!: QueryList<Pane>; get serializedPanes(): string { return this.topLevelPanes ? this.topLevelPanes.map((p) => p.id).join(', ') : ''; } get serializedNestedPanes(): string { return this.arbitraryNestedPanes ? this.arbitraryNestedPanes.map((p) => p.id).join(', ') : ''; } } @Component({ selector: 'example-app', template: ` <tab> <pane id="1"></pane> <pane id="2"></pane> <pane id="3" *ngIf="shouldShow"> <tab> <pane id="3_1"></pane> <pane id="3_2"></pane> </tab> </pane> </tab> <button (click)="show()">Show 3</button> `, standalone: false, }) export class ContentChildrenComp { shouldShow = false; show() { this.shouldShow = true; } } // #enddocregion
{ "end_byte": 1554, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/contentChildren/content_children_example.ts" }
angular/packages/examples/core/di/ts/contentChildren/content_children_howto.ts_0_668
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion HowTo import {AfterContentInit, ContentChildren, Directive, QueryList} from '@angular/core'; @Directive({ selector: 'child-directive', standalone: false, }) class ChildDirective {} @Directive({ selector: 'someDir', standalone: false, }) class SomeDir implements AfterContentInit { @ContentChildren(ChildDirective) contentChildren!: QueryList<ChildDirective>; ngAfterContentInit() { // contentChildren is set } } // #enddocregion
{ "end_byte": 668, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/contentChildren/content_children_howto.ts" }
angular/packages/examples/core/di/ts/contentChildren/e2e_test/content_children_spec.ts_0_1194
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; describe('contentChildren example', () => { afterEach(verifyNoBrowserErrors); let button: ElementFinder; let resultTopLevel: ElementFinder; let resultNested: ElementFinder; beforeEach(() => { browser.get('/di/contentChildren'); button = element(by.css('button')); resultTopLevel = element(by.css('.top-level')); resultNested = element(by.css('.nested')); }); it('should query content children', () => { expect(resultTopLevel.getText()).toEqual('Top level panes: 1, 2'); button.click(); expect(resultTopLevel.getText()).toEqual('Top level panes: 1, 2, 3'); }); it('should query nested content children', () => { expect(resultNested.getText()).toEqual('Arbitrary nested panes: 1, 2'); button.click(); expect(resultNested.getText()).toEqual('Arbitrary nested panes: 1, 2, 3, 3_1, 3_2'); }); });
{ "end_byte": 1194, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/contentChildren/e2e_test/content_children_spec.ts" }
angular/packages/examples/core/di/ts/viewChildren/view_children_howto.ts_0_689
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion HowTo import {AfterViewInit, Component, Directive, QueryList, ViewChildren} from '@angular/core'; @Directive({ selector: 'child-directive', standalone: false, }) class ChildDirective {} @Component({ selector: 'someCmp', templateUrl: 'someCmp.html', standalone: false, }) class SomeCmp implements AfterViewInit { @ViewChildren(ChildDirective) viewChildren!: QueryList<ChildDirective>; ngAfterViewInit() { // viewChildren is set } } // #enddocregion
{ "end_byte": 689, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/viewChildren/view_children_howto.ts" }
angular/packages/examples/core/di/ts/viewChildren/module.ts_0_555
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {Pane, ViewChildrenComp} from './view_children_example'; @NgModule({ imports: [BrowserModule], declarations: [ViewChildrenComp, Pane], bootstrap: [ViewChildrenComp], }) export class AppModule {} export {ViewChildrenComp as AppComponent};
{ "end_byte": 555, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/viewChildren/module.ts" }
angular/packages/examples/core/di/ts/viewChildren/view_children_example.ts_0_1214
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {AfterViewInit, Component, Directive, Input, QueryList, ViewChildren} from '@angular/core'; @Directive({ selector: 'pane', standalone: false, }) export class Pane { @Input() id!: string; } @Component({ selector: 'example-app', template: ` <pane id="1"></pane> <pane id="2"></pane> <pane id="3" *ngIf="shouldShow"></pane> <button (click)="show()">Show 3</button> <div>panes: {{ serializedPanes }}</div> `, standalone: false, }) export class ViewChildrenComp implements AfterViewInit { @ViewChildren(Pane) panes!: QueryList<Pane>; serializedPanes: string = ''; shouldShow = false; show() { this.shouldShow = true; } ngAfterViewInit() { this.calculateSerializedPanes(); this.panes.changes.subscribe((r) => { this.calculateSerializedPanes(); }); } calculateSerializedPanes() { setTimeout(() => { this.serializedPanes = this.panes.map((p) => p.id).join(', '); }, 0); } } // #enddocregion
{ "end_byte": 1214, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/viewChildren/view_children_example.ts" }
angular/packages/examples/core/di/ts/viewChildren/e2e_test/view_children_spec.ts_0_797
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; describe('viewChildren example', () => { afterEach(verifyNoBrowserErrors); let button: ElementFinder; let result: ElementFinder; beforeEach(() => { browser.get('/di/viewChildren'); button = element(by.css('button')); result = element(by.css('div')); }); it('should query view children', () => { expect(result.getText()).toEqual('panes: 1, 2'); button.click(); expect(result.getText()).toEqual('panes: 1, 2, 3'); }); });
{ "end_byte": 797, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/di/ts/viewChildren/e2e_test/view_children_spec.ts" }
angular/packages/examples/core/testability/ts/whenStable/testability_example.ts_0_815
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; @Component({ selector: 'example-app', template: ` <button class="start-button" (click)="start()">Start long-running task</button> <div class="status">Status: {{ status }}</div> `, standalone: false, }) export class StableTestCmp { status = 'none'; start() { this.status = 'running'; setTimeout(() => { this.status = 'done'; }, 5000); } } @NgModule({imports: [BrowserModule], declarations: [StableTestCmp], bootstrap: [StableTestCmp]}) export class AppModule {}
{ "end_byte": 815, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/testability/ts/whenStable/testability_example.ts" }
angular/packages/examples/core/testability/ts/whenStable/module.ts_0_283
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export {AppModule, StableTestCmp as AppComponent} from './testability_example';
{ "end_byte": 283, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/testability/ts/whenStable/module.ts" }
angular/packages/examples/core/testability/ts/whenStable/e2e_test/testability_example_spec.ts_0_1526
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; // Declare the global "window" and "document" constant since we don't want to add the "dom" // TypeScript lib for the e2e specs that execute code in the browser and reference such // global constants. declare const window: any; declare const document: any; describe('testability example', () => { afterEach(verifyNoBrowserErrors); describe('using task tracking', () => { const URL = '/testability/whenStable/'; it('times out with a list of tasks', (done) => { browser.get(URL); browser.ignoreSynchronization = true; // Script that runs in the browser and calls whenStable with a timeout. let waitWithResultScript = function (done: any) { let rootEl = document.querySelector('example-app'); let testability = window.getAngularTestability(rootEl); testability.whenStable(() => { done(); }, 1000); }; element(by.css('.start-button')).click(); browser.driver.executeAsyncScript(waitWithResultScript).then(() => { expect(element(by.css('.status')).getText()).not.toContain('done'); done(); }); }); afterAll(() => { browser.ignoreSynchronization = false; }); }); });
{ "end_byte": 1526, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/testability/ts/whenStable/e2e_test/testability_example_spec.ts" }
angular/packages/examples/core/animation/ts/dsl/module.ts_0_281
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export {AppModule, MyExpandoCmp as AppComponent} from './animation_example';
{ "end_byte": 281, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/animation/ts/dsl/module.ts" }
angular/packages/examples/core/animation/ts/dsl/animation_example.ts_0_1712
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {animate, state, style, transition, trigger} from '@angular/animations'; import {Component, NgModule} from '@angular/core'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; @Component({ selector: 'example-app', styles: [ ` .toggle-container { background-color: white; border: 10px solid black; width: 200px; text-align: center; line-height: 100px; font-size: 50px; box-sizing: border-box; overflow: hidden; } `, ], animations: [ trigger('openClose', [ state('collapsed, void', style({height: '0px', color: 'maroon', borderColor: 'maroon'})), state('expanded', style({height: '*', borderColor: 'green', color: 'green'})), transition('collapsed <=> expanded', [animate(500, style({height: '250px'})), animate(500)]), ]), ], template: ` <button (click)="expand()">Open</button> <button (click)="collapse()">Closed</button> <hr /> <div class="toggle-container" [@openClose]="stateExpression">Look at this box</div> `, standalone: false, }) export class MyExpandoCmp { // TODO(issue/24571): remove '!'. stateExpression!: string; constructor() { this.collapse(); } expand() { this.stateExpression = 'expanded'; } collapse() { this.stateExpression = 'collapsed'; } } @NgModule({ imports: [BrowserAnimationsModule], declarations: [MyExpandoCmp], bootstrap: [MyExpandoCmp], }) export class AppModule {}
{ "end_byte": 1712, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/animation/ts/dsl/animation_example.ts" }
angular/packages/examples/core/animation/ts/dsl/e2e_test/animation_example_spec.ts_0_937
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {$, browser, by, element, ExpectedConditions} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../test-utils'; function waitForElement(selector: string) { const EC = ExpectedConditions; // Waits for the element with id 'abc' to be present on the dom. browser.wait(EC.presenceOf($(selector)), 20000); } describe('animation example', () => { afterEach(verifyNoBrowserErrors); describe('index view', () => { const URL = '/animation/dsl/'; it('should list out the current collection of items', () => { browser.get(URL); waitForElement('.toggle-container'); expect(element.all(by.css('.toggle-container')).get(0).getText()).toEqual('Look at this box'); }); }); });
{ "end_byte": 937, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/animation/ts/dsl/e2e_test/animation_example_spec.ts" }
angular/packages/examples/core/testing/ts/fake_async.ts_0_1062
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {discardPeriodicTasks, fakeAsync, tick} from '@angular/core/testing'; // #docregion basic describe('this test', () => { it( 'looks async but is synchronous', <any>fakeAsync((): void => { let flag = false; setTimeout(() => { flag = true; }, 100); expect(flag).toBe(false); tick(50); expect(flag).toBe(false); tick(50); expect(flag).toBe(true); }), ); }); // #enddocregion describe('this test', () => { it( 'aborts a periodic timer', <any>fakeAsync((): void => { // This timer is scheduled but doesn't need to complete for the // test to pass (maybe it's a timeout for some operation). // Leaving it will cause the test to fail... setInterval(() => {}, 100); // Unless we clean it up first. discardPeriodicTasks(); }), ); });
{ "end_byte": 1062, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/testing/ts/fake_async.ts" }
angular/packages/examples/core/testing/ts/BUILD.bazel_0_571
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "fake_async_lib", srcs = [ "example_spec.ts", "fake_async.ts", ], deps = [ "//packages/core/testing", "@npm//@types/jasmine", "@npm//@types/node", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":fake_async_lib", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "end_byte": 571, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/testing/ts/BUILD.bazel" }
angular/packages/examples/core/testing/ts/example_spec.ts_0_520
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // Import the "fake_async" example that registers tests which are shown as examples. These need // to be valid tests, so we run them here. Note that we need to add this layer of abstraction here // because the "jasmine_node_test" rule only picks up test files with the "_spec.ts" file suffix. import './fake_async';
{ "end_byte": 520, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/testing/ts/example_spec.ts" }
angular/packages/examples/core/ts/prod_mode/my_component.ts_0_376
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component} from '@angular/core'; @Component({ selector: 'my-component', template: '<h1>My Component</h1>', standalone: false, }) export class MyComponent {}
{ "end_byte": 376, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/ts/prod_mode/my_component.ts" }
angular/packages/examples/core/ts/prod_mode/prod_mode_example.ts_0_629
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {enableProdMode, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {MyComponent} from './my_component'; enableProdMode(); @NgModule({imports: [BrowserModule], declarations: [MyComponent], bootstrap: [MyComponent]}) export class AppModule {} platformBrowserDynamic().bootstrapModule(AppModule);
{ "end_byte": 629, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/core/ts/prod_mode/prod_mode_example.ts" }