_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular/adev/src/content/api-examples/common/ngIf/ts/module.ts_0_3503 | /**
* @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, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Subject} from 'rxjs';
// #docregion NgIfSimple
@Component({
selector: 'ng-if-simple',
template: `
<button (click)="show = !show">{{ show ? 'hide' : 'show' }}</button>
show = {{ show }}
<br />
<div *ngIf="show">Text to show</div>
`,
standalone: false,
})
export class NgIfSimple {
show = true;
}
// #enddocregion
// #docregion NgIfElse
@Component({
selector: 'ng-if-else',
template: `
<button (click)="show = !show">{{ show ? 'hide' : 'show' }}</button>
show = {{ show }}
<br />
<div *ngIf="show; else elseBlock">Text to show</div>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`,
standalone: false,
})
export class NgIfElse {
show = true;
}
// #enddocregion
// #docregion NgIfThenElse
@Component({
selector: 'ng-if-then-else',
template: `
<button (click)="show = !show">{{ show ? 'hide' : 'show' }}</button>
<button (click)="switchPrimary()">Switch Primary</button>
show = {{ show }}
<br />
<div *ngIf="show; then thenBlock; else elseBlock">this is ignored</div>
<ng-template #primaryBlock>Primary text to show</ng-template>
<ng-template #secondaryBlock>Secondary text to show</ng-template>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`,
standalone: false,
})
export class NgIfThenElse implements OnInit {
thenBlock: TemplateRef<any> | null = null;
show = true;
@ViewChild('primaryBlock', {static: true}) primaryBlock: TemplateRef<any> | null = null;
@ViewChild('secondaryBlock', {static: true}) secondaryBlock: TemplateRef<any> | null = null;
switchPrimary() {
this.thenBlock = this.thenBlock === this.primaryBlock ? this.secondaryBlock : this.primaryBlock;
}
ngOnInit() {
this.thenBlock = this.primaryBlock;
}
}
// #enddocregion
// #docregion NgIfAs
@Component({
selector: 'ng-if-as',
template: `
<button (click)="nextUser()">Next User</button>
<br />
<div *ngIf="userObservable | async as user; else loading">
Hello {{ user.last }}, {{ user.first }}!
</div>
<ng-template #loading let-user>Waiting... (user is {{ user | json }})</ng-template>
`,
standalone: false,
})
export class NgIfAs {
userObservable = new Subject<{first: string; last: string}>();
first = ['John', 'Mike', 'Mary', 'Bob'];
firstIndex = 0;
last = ['Smith', 'Novotny', 'Angular'];
lastIndex = 0;
nextUser() {
let first = this.first[this.firstIndex++];
if (this.firstIndex >= this.first.length) this.firstIndex = 0;
let last = this.last[this.lastIndex++];
if (this.lastIndex >= this.last.length) this.lastIndex = 0;
this.userObservable.next({first, last});
}
}
// #enddocregion
@Component({
selector: 'example-app',
template: `
<ng-if-simple></ng-if-simple>
<hr />
<ng-if-else></ng-if-else>
<hr />
<ng-if-then-else></ng-if-then-else>
<hr />
<ng-if-as></ng-if-as>
<hr />
`,
standalone: false,
})
export class AppComponent {}
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, NgIfSimple, NgIfElse, NgIfThenElse, NgIfAs],
})
export class AppModule {}
| {
"end_byte": 3503,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/ngIf/ts/module.ts"
} |
angular/adev/src/content/api-examples/common/ngIf/ts/e2e_test/ngIf_spec.ts_0_2783 | /**
* @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 '../../../../../../../../packages/examples/test-utils/index';
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('ngIf', () => {
const URL = '/ngIf';
afterEach(verifyNoBrowserErrors);
describe('ng-if-simple', () => {
let comp = 'ng-if-simple';
it('should hide/show content', () => {
browser.get(URL);
waitForElement(comp);
expect(element.all(by.css(comp)).get(0).getText()).toEqual('hide show = true\nText to show');
element(by.css(comp + ' button')).click();
expect(element.all(by.css(comp)).get(0).getText()).toEqual('show show = false');
});
});
describe('ng-if-else', () => {
let comp = 'ng-if-else';
it('should hide/show content', () => {
browser.get(URL);
waitForElement(comp);
expect(element.all(by.css(comp)).get(0).getText()).toEqual('hide show = true\nText to show');
element(by.css(comp + ' button')).click();
expect(element.all(by.css(comp)).get(0).getText()).toEqual(
'show show = false\nAlternate text while primary text is hidden',
);
});
});
describe('ng-if-then-else', () => {
let comp = 'ng-if-then-else';
it('should hide/show content', () => {
browser.get(URL);
waitForElement(comp);
expect(element.all(by.css(comp)).get(0).getText()).toEqual(
'hideSwitch Primary show = true\nPrimary text to show',
);
element
.all(by.css(comp + ' button'))
.get(1)
.click();
expect(element.all(by.css(comp)).get(0).getText()).toEqual(
'hideSwitch Primary show = true\nSecondary text to show',
);
element
.all(by.css(comp + ' button'))
.get(0)
.click();
expect(element.all(by.css(comp)).get(0).getText()).toEqual(
'showSwitch Primary show = false\nAlternate text while primary text is hidden',
);
});
});
describe('ng-if-as', () => {
let comp = 'ng-if-as';
it('should hide/show content', () => {
browser.get(URL);
waitForElement(comp);
expect(element.all(by.css(comp)).get(0).getText()).toEqual(
'Next User\nWaiting... (user is null)',
);
element(by.css(comp + ' button')).click();
expect(element.all(by.css(comp)).get(0).getText()).toEqual('Next User\nHello Smith, John!');
});
});
});
| {
"end_byte": 2783,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/ngIf/ts/e2e_test/ngIf_spec.ts"
} |
angular/adev/src/content/api-examples/service-worker/registration-options/ngsw-worker.js_0_516 | /**
* @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
*/
// Mock `ngsw-worker.js` used for testing the examples.
// Immediately takes over and unregisters itself.
self.addEventListener('install', (evt) => evt.waitUntil(self.skipWaiting()));
self.addEventListener('activate', (evt) =>
evt.waitUntil(self.clients.claim().then(() => self.registration.unregister())),
);
| {
"end_byte": 516,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/service-worker/registration-options/ngsw-worker.js"
} |
angular/adev/src/content/api-examples/service-worker/registration-options/main.ts_0_412 | /**
* @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 {AppModule} from './module';
platformBrowserDynamic().bootstrapModule(AppModule);
| {
"end_byte": 412,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/service-worker/registration-options/main.ts"
} |
angular/adev/src/content/api-examples/service-worker/registration-options/module.ts_0_1284 | /**
* @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-duplicate-imports
import {Component} from '@angular/core';
// #docregion registration-options
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServiceWorkerModule, SwRegistrationOptions} from '@angular/service-worker';
// #enddocregion registration-options
import {SwUpdate} from '@angular/service-worker';
// tslint:enable: no-duplicate-imports
@Component({
selector: 'example-app',
template: 'SW enabled: {{ swu.isEnabled }}',
standalone: false,
})
export class AppComponent {
constructor(readonly swu: SwUpdate) {}
}
// #docregion registration-options
@NgModule({
// #enddocregion registration-options
bootstrap: [AppComponent],
declarations: [AppComponent],
// #docregion registration-options
imports: [BrowserModule, ServiceWorkerModule.register('ngsw-worker.js')],
providers: [
{
provide: SwRegistrationOptions,
useFactory: () => ({enabled: location.search.includes('sw=true')}),
},
],
})
export class AppModule {}
// #enddocregion registration-options
| {
"end_byte": 1284,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/service-worker/registration-options/module.ts"
} |
angular/adev/src/content/api-examples/service-worker/registration-options/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/adev/src/content/api-examples/service-worker/registration-options/start-server.js"
} |
angular/adev/src/content/api-examples/service-worker/registration-options/e2e_test/registration-options_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 '../../../../../../../packages/examples/test-utils/index';
describe('SW `SwRegistrationOptions` example', () => {
const pageUrl = '/registration-options';
const appElem = element(by.css('example-app'));
afterEach(verifyNoBrowserErrors);
it('not register the SW by default', () => {
browser.get(pageUrl);
expect(appElem.getText()).toBe('SW enabled: false');
});
it('register the SW when navigating to `?sw=true`', () => {
browser.get(`${pageUrl}?sw=true`);
expect(appElem.getText()).toBe('SW enabled: true');
});
});
| {
"end_byte": 839,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/service-worker/registration-options/e2e_test/registration-options_spec.ts"
} |
angular/adev/src/content/api-examples/service-worker/push/ngsw-worker.js_0_516 | /**
* @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
*/
// Mock `ngsw-worker.js` used for testing the examples.
// Immediately takes over and unregisters itself.
self.addEventListener('install', (evt) => evt.waitUntil(self.skipWaiting()));
self.addEventListener('activate', (evt) =>
evt.waitUntil(self.clients.claim().then(() => self.registration.unregister())),
);
| {
"end_byte": 516,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/service-worker/push/ngsw-worker.js"
} |
angular/adev/src/content/api-examples/service-worker/push/main.ts_0_412 | /**
* @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 {AppModule} from './module';
platformBrowserDynamic().bootstrapModule(AppModule);
| {
"end_byte": 412,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/service-worker/push/main.ts"
} |
angular/adev/src/content/api-examples/service-worker/push/module.ts_0_1752 | /**
* @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-duplicate-imports
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ServiceWorkerModule} from '@angular/service-worker';
// #docregion inject-sw-push
import {SwPush} from '@angular/service-worker';
// #enddocregion inject-sw-push
// tslint:enable: no-duplicate-imports
const PUBLIC_VAPID_KEY_OF_SERVER = '...';
@Component({
selector: 'example-app',
template: 'SW enabled: {{ swPush.isEnabled }}',
standalone: false,
})
// #docregion inject-sw-push
export class AppComponent {
constructor(readonly swPush: SwPush) {}
// #enddocregion inject-sw-push
// #docregion subscribe-to-push
private async subscribeToPush() {
try {
const sub = await this.swPush.requestSubscription({
serverPublicKey: PUBLIC_VAPID_KEY_OF_SERVER,
});
// TODO: Send to server.
} catch (err) {
console.error('Could not subscribe due to:', err);
}
}
// #enddocregion subscribe-to-push
private subscribeToNotificationClicks() {
// #docregion subscribe-to-notification-clicks
this.swPush.notificationClicks.subscribe(({action, notification}) => {
// TODO: Do something in response to notification click.
});
// #enddocregion subscribe-to-notification-clicks
}
// #docregion inject-sw-push
}
// #enddocregion inject-sw-push
@NgModule({
bootstrap: [AppComponent],
declarations: [AppComponent],
imports: [BrowserModule, ServiceWorkerModule.register('ngsw-worker.js')],
})
export class AppModule {}
| {
"end_byte": 1752,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/service-worker/push/module.ts"
} |
angular/adev/src/content/api-examples/service-worker/push/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/adev/src/content/api-examples/service-worker/push/start-server.js"
} |
angular/adev/src/content/api-examples/service-worker/push/e2e_test/push_spec.ts_0_630 | /**
* @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 '../../../../../../../packages/examples/test-utils/index';
describe('SW `SwPush` example', () => {
const pageUrl = '/push';
const appElem = element(by.css('example-app'));
afterEach(verifyNoBrowserErrors);
it('should be enabled', () => {
browser.get(pageUrl);
expect(appElem.getText()).toBe('SW enabled: true');
});
});
| {
"end_byte": 630,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/service-worker/push/e2e_test/push_spec.ts"
} |
angular/adev/src/content/api-examples/platform-browser/BUILD.bazel_0_435 | load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "platform_browser_examples",
srcs = glob(["**/*.ts"]),
deps = [
"//packages/compiler",
"//packages/core",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"**/*.ts",
]),
)
| {
"end_byte": 435,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/platform-browser/BUILD.bazel"
} |
angular/adev/src/content/api-examples/platform-browser/dom/debug/ts/by/by.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 {DebugElement} from '@angular/core';
import {By} from '@angular/platform-browser';
let debugElement: DebugElement = undefined!;
class MyDirective {}
// #docregion by_all
debugElement.query(By.all());
// #enddocregion
// #docregion by_css
debugElement.query(By.css('[attribute]'));
// #enddocregion
// #docregion by_directive
debugElement.query(By.directive(MyDirective));
// #enddocregion
| {
"end_byte": 604,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/platform-browser/dom/debug/ts/by/by.ts"
} |
angular/adev/src/content/api-examples/platform-browser/dom/debug/ts/debug_element_view_listener/providers.ts_0_635 | /**
* @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';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
@Component({
selector: 'my-component',
template: 'text',
standalone: false,
})
class MyAppComponent {}
@NgModule({imports: [BrowserModule], bootstrap: [MyAppComponent]})
class AppModule {}
platformBrowserDynamic().bootstrapModule(AppModule);
| {
"end_byte": 635,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/platform-browser/dom/debug/ts/debug_element_view_listener/providers.ts"
} |
angular/adev/src/content/api-examples/router/route_functional_guards.ts_0_3607 | /**
* @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, inject, Injectable} from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';
import {
ActivatedRoute,
ActivatedRouteSnapshot,
CanActivateChildFn,
CanActivateFn,
CanMatchFn,
provideRouter,
ResolveFn,
Route,
RouterStateSnapshot,
UrlSegment,
} from '@angular/router';
@Component({
template: '',
standalone: false,
})
export class App {}
@Component({
template: '',
standalone: false,
})
export class TeamComponent {}
// #docregion CanActivateFn
@Injectable()
class UserToken {}
@Injectable()
class PermissionsService {
canActivate(currentUser: UserToken, userId: string): boolean {
return true;
}
canMatch(currentUser: UserToken): boolean {
return true;
}
}
const canActivateTeam: CanActivateFn = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
) => {
return inject(PermissionsService).canActivate(inject(UserToken), route.params['id']);
};
// #enddocregion
// #docregion CanActivateFnInRoute
bootstrapApplication(App, {
providers: [
provideRouter([
{
path: 'team/:id',
component: TeamComponent,
canActivate: [canActivateTeam],
},
]),
],
});
// #enddocregion
// #docregion CanActivateChildFn
const canActivateChildExample: CanActivateChildFn = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
) => {
return inject(PermissionsService).canActivate(inject(UserToken), route.params['id']);
};
bootstrapApplication(App, {
providers: [
provideRouter([
{
path: 'team/:id',
component: TeamComponent,
canActivateChild: [canActivateChildExample],
children: [],
},
]),
],
});
// #enddocregion
// #docregion CanDeactivateFn
@Component({
template: '',
standalone: false,
})
export class UserComponent {
hasUnsavedChanges = true;
}
bootstrapApplication(App, {
providers: [
provideRouter([
{
path: 'user/:id',
component: UserComponent,
canDeactivate: [(component: UserComponent) => !component.hasUnsavedChanges],
},
]),
],
});
// #enddocregion
// #docregion CanMatchFn
const canMatchTeam: CanMatchFn = (route: Route, segments: UrlSegment[]) => {
return inject(PermissionsService).canMatch(inject(UserToken));
};
bootstrapApplication(App, {
providers: [
provideRouter([
{
path: 'team/:id',
component: TeamComponent,
canMatch: [canMatchTeam],
},
]),
],
});
// #enddocregion
// #docregion ResolveDataUse
@Component({
template: '',
standalone: false,
})
export class HeroDetailComponent {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.data.subscribe(({hero}) => {
// do something with your resolved data ...
});
}
}
// #enddocregion
// #docregion ResolveFn
interface Hero {
name: string;
}
@Injectable()
export class HeroService {
getHero(id: string) {
return {name: `Superman-${id}`};
}
}
export const heroResolver: ResolveFn<Hero> = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
) => {
return inject(HeroService).getHero(route.paramMap.get('id')!);
};
bootstrapApplication(App, {
providers: [
provideRouter([
{
path: 'detail/:id',
component: HeroDetailComponent,
resolve: {hero: heroResolver},
},
]),
],
});
// #enddocregion
| {
"end_byte": 3607,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/router/route_functional_guards.ts"
} |
angular/adev/src/content/api-examples/router/activated-route/main.ts_0_412 | /**
* @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 {AppModule} from './module';
platformBrowserDynamic().bootstrapModule(AppModule);
| {
"end_byte": 412,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/router/activated-route/main.ts"
} |
angular/adev/src/content/api-examples/router/activated-route/module.ts_0_1289 | /**
* @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 activated-route
import {Component, NgModule} from '@angular/core';
// #enddocregion activated-route
import {BrowserModule} from '@angular/platform-browser';
// #docregion activated-route
import {ActivatedRoute, RouterModule} from '@angular/router';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
// #enddocregion activated-route
// #docregion activated-route
@Component({
// #enddocregion activated-route
selector: 'example-app',
template: '...',
standalone: false,
})
export class ActivatedRouteComponent {
constructor(route: ActivatedRoute) {
const id: Observable<string> = route.params.pipe(map((p) => p['id']));
const url: Observable<string> = route.url.pipe(map((segments) => segments.join('')));
// route.data includes both `data` and `resolve`
const user = route.data.pipe(map((d) => d['user']));
}
}
// #enddocregion activated-route
@NgModule({
imports: [BrowserModule, RouterModule.forRoot([])],
declarations: [ActivatedRouteComponent],
bootstrap: [ActivatedRouteComponent],
})
export class AppModule {}
| {
"end_byte": 1289,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/router/activated-route/module.ts"
} |
angular/adev/src/content/api-examples/router/activated-route/BUILD.bazel_0_826 | load("//tools:defaults.bzl", "esbuild", "http_server", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "router_activated_route_examples",
srcs = glob(
["**/*.ts"],
),
deps = [
"//packages/core",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
"//packages/router",
"//packages/zone.js/lib",
"@npm//rxjs",
],
)
esbuild(
name = "app_bundle",
entry_point = ":main.ts",
deps = [":router_activated_route_examples"],
)
http_server(
name = "devserver",
srcs = ["//packages/examples:index.html"],
additional_root_paths = ["angular/packages/examples"],
deps = [":app_bundle"],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"**/*.ts",
]),
)
| {
"end_byte": 826,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/router/activated-route/BUILD.bazel"
} |
angular/adev/src/content/api-examples/router/utils/functional_guards.ts_0_802 | /**
* @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} from '@angular/core';
import {mapToCanActivate, mapToResolve, Route} from '@angular/router';
// #docregion CanActivate
@Injectable({providedIn: 'root'})
export class AdminGuard {
canActivate() {
return true;
}
}
const route: Route = {
path: 'admin',
canActivate: mapToCanActivate([AdminGuard]),
};
// #enddocregion
// #docregion Resolve
@Injectable({providedIn: 'root'})
export class ResolveUser {
resolve() {
return {name: 'Bob'};
}
}
const userRoute: Route = {
path: 'user',
resolve: {
user: mapToResolve(ResolveUser),
},
};
// #enddocregion
| {
"end_byte": 802,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/router/utils/functional_guards.ts"
} |
angular/adev/src/content/api-examples/router/testing/BUILD.bazel_0_717 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.spec.ts"]),
deps = [
"//packages/common",
"//packages/core",
"//packages/core/testing",
"//packages/router",
"//packages/router/testing",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"**/*.ts",
]),
)
| {
"end_byte": 717,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/router/testing/BUILD.bazel"
} |
angular/adev/src/content/api-examples/router/testing/test/router_testing_harness_examples.spec.ts_0_3034 | /**
* @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 {AsyncPipe} from '@angular/common';
import {Component, inject} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ActivatedRoute, CanActivateFn, provideRouter, Router} from '@angular/router';
import {RouterTestingHarness} from '@angular/router/testing';
describe('navigate for test examples', () => {
// #docregion RoutedComponent
it('navigates to routed component', async () => {
@Component({standalone: true, template: 'hello {{name}}'})
class TestCmp {
name = 'world';
}
TestBed.configureTestingModule({
providers: [provideRouter([{path: '', component: TestCmp}])],
});
const harness = await RouterTestingHarness.create();
const activatedComponent = await harness.navigateByUrl('/', TestCmp);
expect(activatedComponent).toBeInstanceOf(TestCmp);
expect(harness.routeNativeElement?.innerHTML).toContain('hello world');
});
// #enddocregion
it('testing a guard', async () => {
@Component({standalone: true, template: ''})
class AdminComponent {}
@Component({standalone: true, template: ''})
class LoginComponent {}
// #docregion Guard
let isLoggedIn = false;
const isLoggedInGuard: CanActivateFn = () => {
return isLoggedIn ? true : inject(Router).parseUrl('/login');
};
TestBed.configureTestingModule({
providers: [
provideRouter([
{path: 'admin', canActivate: [isLoggedInGuard], component: AdminComponent},
{path: 'login', component: LoginComponent},
]),
],
});
const harness = await RouterTestingHarness.create('/admin');
expect(TestBed.inject(Router).url).toEqual('/login');
isLoggedIn = true;
await harness.navigateByUrl('/admin');
expect(TestBed.inject(Router).url).toEqual('/admin');
// #enddocregion
});
it('test a ActivatedRoute', async () => {
// #docregion ActivatedRoute
@Component({
standalone: true,
imports: [AsyncPipe],
template: `
search: {{ (route.queryParams | async)?.query }}
`,
})
class SearchCmp {
constructor(
readonly route: ActivatedRoute,
readonly router: Router,
) {}
async searchFor(thing: string) {
await this.router.navigate([], {queryParams: {query: thing}});
}
}
TestBed.configureTestingModule({
providers: [provideRouter([{path: 'search', component: SearchCmp}])],
});
const harness = await RouterTestingHarness.create();
const activatedComponent = await harness.navigateByUrl('/search', SearchCmp);
await activatedComponent.searchFor('books');
harness.detectChanges();
expect(TestBed.inject(Router).url).toEqual('/search?query=books');
expect(harness.routeNativeElement?.innerHTML).toContain('books');
// #enddocregion
});
});
| {
"end_byte": 3034,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/router/testing/test/router_testing_harness_examples.spec.ts"
} |
angular/adev/src/content/cli/index.md_0_5799 | # CLI Overview and Command Reference
The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications directly from a command shell.
## Installing Angular CLI
Major versions of Angular CLI follow the supported major version of Angular, but minor versions can be released separately.
Install the CLI using the `npm` package manager:
<code-example format="shell" language="shell">
npm install -g @angular/cli<aio-angular-dist-tag class="pln"></aio-angular-dist-tag>
</code-example>
For details about changes between versions, and information about updating from previous releases, see the Releases tab on GitHub: https://github.com/angular/angular-cli/releases
## Basic workflow
Invoke the tool on the command line through the `ng` executable.
Online help is available on the command line.
Enter the following to list commands or options for a given command \(such as [new](cli/new)\) with a short description.
<code-example format="shell" language="shell">
ng --help
ng new --help
</code-example>
To create, build, and serve a new, basic Angular project on a development server, go to the parent directory of your new workspace use the following commands:
<code-example format="shell" language="shell">
ng new my-first-project
cd my-first-project
ng serve
</code-example>
In your browser, open http://localhost:4200/ to see the new application run.
When you use the [ng serve](cli/serve) command to build an application and serve it locally, the server automatically rebuilds the application and reloads the page when you change any of the source files.
<div class="alert is-helpful">
When you run `ng new my-first-project` a new folder, named `my-first-project`, will be created in the current working directory.
Since you want to be able to create files inside that folder, make sure you have sufficient rights in the current working directory before running the command.
If the current working directory is not the right place for your project, you can change to a more appropriate directory by running `cd <path-to-other-directory>`.
</div>
## Workspaces and project files
The [ng new](cli/new) command creates an *Angular workspace* folder and generates a new application skeleton.
A workspace can contain multiple applications and libraries.
The initial application created by the [ng new](cli/new) command is at the top level of the workspace.
When you generate an additional application or library in a workspace, it goes into a `projects/` subfolder.
A newly generated application contains the source files for a root module, with a root component and template.
Each application has a `src` folder that contains the logic, data, and assets.
You can edit the generated files directly, or add to and modify them using CLI commands.
Use the [ng generate](cli/generate) command to add new files for additional components and services, and code for new pipes, directives, and so on.
Commands such as [add](cli/add) and [generate](cli/generate), which create or operate on applications and libraries, must be executed from within a workspace or project folder.
* See more about the [Workspace file structure](guide/file-structure).
### Workspace and project configuration
A single workspace configuration file, `angular.json`, is created at the top level of the workspace.
This is where you can set per-project defaults for CLI command options, and specify configurations to use when the CLI builds a project for different targets.
The [ng config](cli/config) command lets you set and retrieve configuration values from the command line, or you can edit the `angular.json` file directly.
<div class="alert is-helpful">
**NOTE**: <br />
Option names in the configuration file must use [camelCase](guide/glossary#case-types), while option names supplied to commands must be dash-case.
</div>
* See more about [Workspace Configuration](guide/workspace-config).
## CLI command-language syntax
Command syntax is shown as follows:
`ng` *<command-name>* *<required-arg>* [*optional-arg*] `[options]`
* Most commands, and some options, have aliases.
Aliases are shown in the syntax statement for each command.
* Option names are prefixed with a double dash \(`--`\) characters.
Option aliases are prefixed with a single dash \(`-`\) character.
Arguments are not prefixed.
For example:
<code-example format="shell" language="shell">
ng build my-app -c production
</code-example>
* Typically, the name of a generated artifact can be given as an argument to the command or specified with the `--name` option.
* Arguments and option names must be given in [dash-case](guide/glossary#case-types).
For example: `--my-option-name`
### Boolean options
Boolean options have two forms: `--this-option` sets the flag to `true`, `--no-this-option` sets it to `false`.
If neither option is supplied, the flag remains in its default state, as listed in the reference documentation.
### Array options
Array options can be provided in two forms: `--option value1 value2` or `--option value1 --option value2`.
### Relative paths
Options that specify files can be given as absolute paths, or as paths relative to the current working directory, which is generally either the workspace or project root.
### Schematics
The [ng generate](cli/generate) and [ng add](cli/add) commands take, as an argument, the artifact or library to be generated or added to the current project.
In addition to any general options, each artifact or library defines its own options in a *schematic*.
Schematic options are supplied to the command in the same format as immediate command options.
<!-- links -->
<!-- external links -->
<!-- end links -->
@reviewed 2022-02-28
| {
"end_byte": 5799,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/cli/index.md"
} |
angular/adev/src/content/cli/BUILD.bazel_0_288 | package(default_visibility = ["//visibility:public"])
filegroup(
name = "cli",
srcs = glob(
["**"],
exclude = [
"BUILD.bazel",
],
) + [
"//adev/src/content/cli/help",
"//adev/src/content/cli/help:build-info.json",
],
)
| {
"end_byte": 288,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/cli/BUILD.bazel"
} |
angular/adev/src/content/cli/help/BUILD.bazel_0_499 | load("//adev/shared-docs/pipeline/api-gen/rendering:render_api_to_html.bzl", "render_api_to_html")
package(default_visibility = ["//visibility:public"])
exports_files(["build-info.json"])
filegroup(
name = "help",
srcs = glob(
["*"],
exclude = [
# Exlucde build-info.json as it is not a help entry.
"build-info.json",
"BUILD.bazel",
],
),
)
render_api_to_html(
name = "cli_docs",
srcs = [
":help",
],
)
| {
"end_byte": 499,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/cli/help/BUILD.bazel"
} |
angular/adev/src/content/examples/cli-builder/BUILD.bazel_0_30 | exports_files(glob(["**/*"]))
| {
"end_byte": 30,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/cli-builder/BUILD.bazel"
} |
angular/adev/src/content/examples/cli-builder/src/my-builder.spec.ts_0_1822 | // #docregion
import {Architect} from '@angular-devkit/architect';
import {TestingArchitectHost} from '@angular-devkit/architect/testing';
import {schema} from '@angular-devkit/core';
import {promises as fs} from 'fs';
import {join} from 'path';
describe('Copy File Builder', () => {
let architect: Architect;
let architectHost: TestingArchitectHost;
beforeEach(async () => {
const registry = new schema.CoreSchemaRegistry();
registry.addPostTransform(schema.transforms.addUndefinedDefaults);
// TestingArchitectHost() takes workspace and current directories.
// Since we don't use those, both are the same in this case.
architectHost = new TestingArchitectHost(__dirname, __dirname);
architect = new Architect(architectHost, registry);
// This will either take a Node package name, or a path to the directory
// for the package.json file.
await architectHost.addBuilderFromPackage(join(__dirname, '..'));
});
it('can copy files', async () => {
// A "run" can have multiple outputs, and contains progress information.
const run = await architect.scheduleBuilder('@example/copy-file:copy', {
source: 'package.json',
destination: 'package-copy.json',
});
// The "result" member (of type BuilderOutput) is the next output.
const output = await run.result;
// Stop the builder from running. This stops Architect from keeping
// the builder-associated states in memory, since builders keep waiting
// to be scheduled.
await run.stop();
// Expect that the copied file is the same as its source.
const sourceContent = await fs.readFile('package.json', 'utf8');
const destinationContent = await fs.readFile('package-copy.json', 'utf8');
expect(destinationContent).toBe(sourceContent);
});
});
// #enddocregion
| {
"end_byte": 1822,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/cli-builder/src/my-builder.spec.ts"
} |
angular/adev/src/content/examples/cli-builder/src/my-builder.ts_0_1311 | // #docplaster
// #docregion builder, builder-skeleton
import {BuilderContext, BuilderOutput, createBuilder} from '@angular-devkit/architect';
import {JsonObject} from '@angular-devkit/core';
// #enddocregion builder-skeleton
import {promises as fs} from 'fs';
// #docregion builder-skeleton
interface Options extends JsonObject {
source: string;
destination: string;
}
export default createBuilder(copyFileBuilder);
async function copyFileBuilder(options: Options, context: BuilderContext): Promise<BuilderOutput> {
// #enddocregion builder, builder-skeleton
// #docregion progress-reporting
context.reportStatus(`Copying ${options.source} to ${options.destination}.`);
// #docregion builder, handling-output
try {
// #docregion report-status
await fs.copyFile(options.source, options.destination);
// #enddocregion report-status
} catch (err) {
// #enddocregion builder
context.logger.error('Failed to copy file.');
// #docregion builder
return {
success: false,
error: (err as Error).message,
};
}
// #enddocregion builder, handling-output
context.reportStatus('Done.');
// #docregion builder
return {success: true};
// #enddocregion progress-reporting
// #docregion builder-skeleton
}
// #enddocregion builder, builder-skeleton
| {
"end_byte": 1311,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/cli-builder/src/my-builder.ts"
} |
angular/adev/src/content/examples/injection-token/BUILD.bazel_0_54 | package(default_visibility = ["//visibility:public"])
| {
"end_byte": 54,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/injection-token/BUILD.bazel"
} |
angular/adev/src/content/examples/injection-token/e2e/src/app.e2e-spec.ts_0_262 | /*
* This example project is special in that it is not a cli app.
*
* This is an empty placeholder file to ensure that example tests correctly runs
* tests for this project.
*
* TODO: Fix our infrastructure/tooling, so that this hack is not necessary.
*/
| {
"end_byte": 262,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/injection-token/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/injection-token/src/main.ts_0_744 | // TODO: Add unit tests for this file.
/* eslint-disable @angular-eslint/no-output-native */
// #docregion
import {Injector, InjectionToken} from '@angular/core';
interface MyInterface {
someProperty: string;
}
// #docregion InjectionToken
const TOKEN = new InjectionToken<MyInterface>('SomeToken');
// Setting up the provider using the same token instance
const providers = [
{provide: TOKEN, useValue: {someProperty: 'exampleValue'}}, // Mock value for MyInterface
];
// Creating the injector with the provider
const injector = Injector.create({providers});
// Retrieving the value using the same token instance
const myInterface = injector.get(TOKEN);
// myInterface is inferred to be MyInterface.
// #enddocregion InjectionToken
| {
"end_byte": 744,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/injection-token/src/main.ts"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/BUILD.bazel_0_183 | package(default_visibility = ["//visibility:public"])
exports_files([
"src/app/app.component.html",
"src/app/app.routes.ts",
"src/app/profile/profile.component.html",
])
| {
"end_byte": 183,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/BUILD.bazel"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/e2e/src/app.e2e-spec.ts_0_304 | import {browser, element, by} from 'protractor';
describe('Routing with Custom Matching', () => {
beforeAll(() => browser.get(''));
it('should display Routing with Custom Matching ', async () => {
expect(await element(by.css('h2')).getText()).toEqual('Routing with Custom Matching');
});
});
| {
"end_byte": 304,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/index.html_0_161 | <!DOCTYPE html>
<html lang="en">
<head>
<base href="/">
<title>Angular App</title>
</head>
<body>
<app-root>loading</app-root>
</body>
</html>
| {
"end_byte": 161,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/index.html"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/main.ts_0_221 | // #docregion
import {bootstrapApplication} from '@angular/platform-browser';
import {AppComponent} from './app/app.component';
import {appConfig} from './app/app.config';
bootstrapApplication(AppComponent, appConfig);
| {
"end_byte": 221,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/main.ts"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/app/app.component.html_0_124 | <h2>Routing with Custom Matching</h2>
Navigate to <a routerLink="/@Angular">my profile</a>
<router-outlet></router-outlet> | {
"end_byte": 124,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/app/app.component.html"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/app/app.routes.ts_0_465 | import {Routes, UrlSegment} from '@angular/router';
import {ProfileComponent} from './profile/profile.component';
export const routes: Routes = [
// #docregion matcher
{
matcher: (url) => {
if (url.length === 1 && url[0].path.match(/^@[\w]+$/gm)) {
return {consumed: url, posParams: {username: new UrlSegment(url[0].path.slice(1), {})}};
}
return null;
},
component: ProfileComponent,
},
// #enddocregion matcher
];
| {
"end_byte": 465,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/app/app.routes.ts"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/app/app.component.ts_0_352 | import {Component, VERSION} from '@angular/core';
import {RouterLink, RouterOutlet} from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
}
| {
"end_byte": 352,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/app/app.component.ts"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/app/app.config.ts_0_401 | import {ApplicationConfig} from '@angular/core';
import {provideProtractorTestingSupport} from '@angular/platform-browser';
import {provideRouter, withComponentInputBinding} from '@angular/router';
import {routes} from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withComponentInputBinding()),
provideProtractorTestingSupport(),
],
};
| {
"end_byte": 401,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/app/app.config.ts"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/app/app.component.css_0_26 | p {
font-family: Lato;
} | {
"end_byte": 26,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/app/app.component.css"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/app/profile/profile.component.html_0_34 | <p>
Hello {{ username }}!
</p> | {
"end_byte": 34,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/app/profile/profile.component.html"
} |
angular/adev/src/content/examples/routing-with-urlmatcher/src/app/profile/profile.component.ts_0_261 | import {Component, Input} from '@angular/core';
@Component({
selector: 'app-profile',
standalone: true,
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css'],
})
export class ProfileComponent {
@Input() username!: string;
}
| {
"end_byte": 261,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/routing-with-urlmatcher/src/app/profile/profile.component.ts"
} |
angular/adev/src/content/examples/forms/BUILD.bazel_0_388 | package(default_visibility = ["//visibility:public"])
exports_files([
"src/app/actor.ts",
"src/app/actor-form/actor-form.component.html",
"src/app/actor-form/actor-form.component.ts",
"src/app/app.component.html",
"src/app/app.component.ts",
"src/app/app.module.ts",
"src/assets/forms.css",
"src/index.html",
"src/main.ts",
"src/styles.1.css",
])
| {
"end_byte": 388,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/BUILD.bazel"
} |
angular/adev/src/content/examples/forms/e2e/src/app.e2e-spec.ts_0_2105 | import {browser, element, by} from 'protractor';
describe('Forms Tests', () => {
beforeEach(() => browser.get(''));
it('should display correct title', async () => {
expect(await element.all(by.css('h1')).get(0).getText()).toEqual('Actor Form');
});
it('should not display message before submit', async () => {
const ele = element(by.css('h2'));
expect(await ele.isDisplayed()).toBe(false);
});
it('should hide form after submit', async () => {
const ele = element.all(by.css('h1')).get(0);
expect(await ele.isDisplayed()).toBe(true);
const b = element.all(by.css('button[type=submit]')).get(0);
await b.click();
expect(await ele.isDisplayed()).toBe(false);
});
it('should display message after submit', async () => {
const b = element.all(by.css('button[type=submit]')).get(0);
await b.click();
expect(await element(by.css('h2')).getText()).toContain('You submitted the following');
});
it('should hide form after submit', async () => {
const studioEle = element.all(by.css('input[name=studio]')).get(0);
expect(await studioEle.isDisplayed()).toBe(true);
const submitButtonEle = element.all(by.css('button[type=submit]')).get(0);
await submitButtonEle.click();
expect(await studioEle.isDisplayed()).toBe(false);
});
it('should reflect submitted data after submit', async () => {
const studioEle = element.all(by.css('input[name=studio]')).get(0);
const value = await studioEle.getAttribute('value');
const test = 'testing 1 2 3';
const newValue = value + test;
await studioEle.sendKeys(test);
expect(await studioEle.getAttribute('value')).toEqual(newValue);
const b = element.all(by.css('button[type=submit]')).get(0);
await b.click();
const studioTextEle = element(by.cssContainingText('div', 'Studio'));
expect(await studioTextEle.isPresent()).toBe(true, 'cannot locate "Studio" label');
const divEle = element(by.cssContainingText('div', newValue));
expect(await divEle.isPresent()).toBe(true, `cannot locate div with this text: ${newValue}`);
});
});
| {
"end_byte": 2105,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/forms/src/index.html_0_501 | <!DOCTYPE html>
<!-- #docregion -->
<html lang="en">
<head>
<title>Hero Form</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css">
<!-- #docregion styles -->
<link rel="stylesheet" href="assets/forms.css">
<!-- #enddocregion styles -->
</head>
<body>
<app-root></app-root>
</body>
</html>
| {
"end_byte": 501,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/index.html"
} |
angular/adev/src/content/examples/forms/src/main.ts_0_228 | // #docregion
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app/app.module';
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch((err) => console.error(err));
| {
"end_byte": 228,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/main.ts"
} |
angular/adev/src/content/examples/forms/src/styles.1.css_0_77 | @import url('https://unpkg.com/[email protected]/dist/css/bootstrap.min.css');
| {
"end_byte": 77,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/styles.1.css"
} |
angular/adev/src/content/examples/forms/src/app/app.component.html_0_34 | <app-actor-form></app-actor-form>
| {
"end_byte": 34,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/app/app.component.html"
} |
angular/adev/src/content/examples/forms/src/app/actor.ts_0_161 | // #docregion
export class Actor {
constructor(
public id: number,
public name: string,
public skill: string,
public studio?: string,
) {}
}
| {
"end_byte": 161,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/app/actor.ts"
} |
angular/adev/src/content/examples/forms/src/app/app.module.ts_0_513 | // #docregion
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
import {ActorFormComponent} from './actor-form/actor-form.component';
@NgModule({
imports: [BrowserModule, CommonModule, FormsModule],
declarations: [AppComponent, ActorFormComponent],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
| {
"end_byte": 513,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/app/app.module.ts"
} |
angular/adev/src/content/examples/forms/src/app/app.component.ts_0_185 | // #docregion
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
standalone: false,
})
export class AppComponent {}
| {
"end_byte": 185,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/app/app.component.ts"
} |
angular/adev/src/content/examples/forms/src/app/actor-form/actor-form.component.ts_0_1273 | // #docplaster
// #docregion , v1, final
import {Component} from '@angular/core';
import {Actor} from '../actor';
@Component({
selector: 'app-actor-form',
templateUrl: './actor-form.component.html',
standalone: false,
})
export class ActorFormComponent {
skills = ['Method Acting', 'Singing', 'Dancing', 'Swordfighting'];
model = new Actor(18, 'Tom Cruise', this.skills[3], 'CW Productions');
// #docregion submitted
submitted = false;
onSubmit() {
this.submitted = true;
}
// #enddocregion submitted
// #enddocregion final
// #enddocregion v1
// #docregion final, new-actor
newActor() {
this.model = new Actor(42, '', '');
}
// #enddocregion final, new-actor
heroine(): Actor {
// #docregion Marilyn
const myActress = new Actor(42, 'Marilyn Monroe', 'Singing');
console.log('My actress is called ' + myActress.name); // "My actress is called Marilyn"
// #enddocregion Marilyn
return myActress;
}
//////// NOT SHOWN IN DOCS ////////
// Reveal in html:
// Name via form.controls = {{showFormControls(actorForm)}}
showFormControls(form: any) {
return form && form.controls.name && form.controls.name.value; // Tom Cruise
}
/////////////////////////////
// #docregion v1, final
}
| {
"end_byte": 1273,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/app/actor-form/actor-form.component.ts"
} |
angular/adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html_0_6133 | <!-- #docplaster -->
<!-- #docregion final -->
<div class="container">
<!-- #docregion edit-div -->
<div [hidden]="submitted">
<h1>Actor Form</h1>
<!-- #docregion ngSubmit -->
<form (ngSubmit)="onSubmit()" #actorForm="ngForm">
<!-- #enddocregion ngSubmit, edit-div -->
<div class="form-group">
<!-- #docregion name-with-error-msg -->
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required [(ngModel)]="model.name" name="name"
#name="ngModel">
<!-- #docregion hidden-error-msg -->
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
<!-- #enddocregion hidden-error-msg -->
Name is required
</div>
<!-- #enddocregion name-with-error-msg -->
</div>
<div class="form-group">
<label for="studio">Studio Affiliation</label>
<input type="text" class="form-control" id="studio"
[(ngModel)]="model.studio" name="studio">
</div>
<div class="form-group">
<label for="skill">Skill</label>
<select class="form-control" id="skill"
required [(ngModel)]="model.skill" name="skill"
#skill="ngModel">
<option *ngFor="let skill of skills" [value]="skill">{{ skill }}</option>
</select>
<div [hidden]="skill.valid || skill.pristine" class="alert alert-danger">
skill is required
</div>
</div>
<!-- #docregion submit-button -->
<button type="submit" class="btn btn-success"
[disabled]="!actorForm.form.valid">Submit</button>
<!-- #enddocregion submit-button -->
<!-- #docregion new-actor-button-form-reset -->
<button type="button" class="btn btn-default"
(click)="newActor(); actorForm.reset()">New Actor</button>
<!-- #enddocregion new-actor-button-form-reset -->
<!-- #enddocregion final -->
<em>with</em> reset
<!-- #docregion new-actor-button-no-reset -->
<button type="button" class="btn btn-default"
(click)="newActor()">New Actor</button>
<!-- #enddocregion new-actor-button-no-reset -->
<em>without</em> reset
<!-- NOT SHOWN IN DOCS -->
<div>
<hr>
Name via form.controls = {{ showFormControls(actorForm) }}
</div>
<!-- - -->
<!-- #docregion final -->
</form>
</div>
<!-- #docregion submitted -->
<div [hidden]="!submitted">
<h2>You submitted the following:</h2>
<div class="row">
<div class="col-xs-3">Name</div>
<div class="col-xs-9">{{ model.name }}</div>
</div>
<div class="row">
<div class="col-xs-3">Studio</div>
<div class="col-xs-9">{{ model.studio }}</div>
</div>
<div class="row">
<div class="col-xs-3">Skill</div>
<div class="col-xs-9">{{ model.skill }}</div>
</div>
<br>
<button type="button" class="btn btn-primary" (click)="submitted=false">
Edit
</button>
</div>
<!-- #enddocregion submitted -->
</div>
<!-- #enddocregion final -->
<!-- ==================================================== -->
<div>
<form>
<!-- #docregion edit-div -->
<!-- ... all of the form ... -->
</form>
</div>
<!-- #enddocregion edit-div -->
<!-- ==================================================== -->
<hr>
<style>
.no-style .ng-valid {
border-left: 1px solid #CCC
}
.no-style .ng-invalid {
border-left: 1px solid #CCC
}
</style>
<div class="no-style" style="margin-left: 4px">
<div class="container">
<h1>Actor Form</h1>
<form>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" required>
</div>
<div class="form-group">
<label for="studio">Studio</label>
<input type="text" class="form-control" id="studio">
</div>
<!-- #docregion skills -->
<div class="form-group">
<label for="skill">Skill</label>
<select class="form-control" id="skill" required>
<option *ngFor="let skill of skills" [value]="skill">{{ skill }}</option>
</select>
</div>
<!-- #enddocregion skills -->
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
<!-- ==================================================== -->
<hr>
<div class="container">
<h1>Actor Form</h1>
<!-- #docregion template-variable-->
<form #actorForm="ngForm">
<!-- #enddocregion template-variable-->
<!-- #docregion ngModel-2-->
{{ model | json }}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name">
</div>
<div class="form-group">
<label for="studio">Studio</label>
<input type="text" class="form-control" id="studio"
[(ngModel)]="model.studio" name="studio">
</div>
<div class="form-group">
<label for="skill">Skill</label>
<select class="form-control" id="skill"
required
[(ngModel)]="model.skill" name="skill">
<option *ngFor="let skill of skills" [value]="skill">{{ skill }}</option>
</select>
</div>
<!-- #enddocregion ngModel-2-->
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
<!-- EXTRA MATERIAL FOR DOCUMENTATION -->
<hr>
<!-- #docregion ngModelName-1 -->
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name">
TODO: remove this: {{ model.name}}
<!-- #enddocregion ngModelName-1 -->
<hr>
<input type="text" class="form-control" id="name"
required
[ngModel]="model.name" name="name"
(ngModelChange)="model.name = $event">
TODO: remove this: {{ model.name}}
</div>
| {
"end_byte": 6133,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html"
} |
angular/adev/src/content/examples/forms/src/assets/forms.css_0_200 | /* #docregion */
.ng-valid[required], .ng-valid.required {
border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}
/* #enddocregion */
| {
"end_byte": 200,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms/src/assets/forms.css"
} |
angular/adev/src/content/examples/schematics-for-libraries/BUILD.bazel_0_532 | package(default_visibility = ["//visibility:public"])
exports_files([
"projects/my-lib/package.json",
"projects/my-lib/schematics/collection.1.json",
"projects/my-lib/schematics/collection.json",
"projects/my-lib/schematics/my-service/index.1.ts",
"projects/my-lib/schematics/my-service/index.ts",
"projects/my-lib/schematics/my-service/schema.json",
"projects/my-lib/schematics/my-service/schema.ts",
"projects/my-lib/schematics/ng-add/index.ts",
"projects/my-lib/tsconfig.schematics.json",
])
| {
"end_byte": 532,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/BUILD.bazel"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.1.ts_0_249 | import {Rule, Tree} from '@angular-devkit/schematics';
import {Schema as MyServiceSchema} from './schema';
// #docregion factory
export function myService(options: MyServiceSchema): Rule {
return (tree: Tree) => tree;
}
// #enddocregion factory
| {
"end_byte": 249,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.1.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/schema.ts_0_180 | export interface Schema {
// The name of the service.
name: string;
// The path to create the service.
path?: string;
// The name of the project.
project?: string;
}
| {
"end_byte": 180,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/schema.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts_0_2248 | // #docplaster
// #docregion schematics-imports, schema-imports, workspace
import {
Rule,
Tree,
SchematicsException,
apply,
url,
applyTemplates,
move,
chain,
mergeWith,
} from '@angular-devkit/schematics';
import {strings, normalize, virtualFs, workspaces} from '@angular-devkit/core';
// #enddocregion schematics-imports
import {Schema as MyServiceSchema} from './schema';
// #enddocregion schema-imports
function createHost(tree: Tree): workspaces.WorkspaceHost {
return {
async readFile(path: string): Promise<string> {
const data = tree.read(path);
if (!data) {
throw new SchematicsException('File not found.');
}
return virtualFs.fileBufferToString(data);
},
async writeFile(path: string, data: string): Promise<void> {
return tree.overwrite(path, data);
},
async isDirectory(path: string): Promise<boolean> {
return !tree.exists(path) && tree.getDir(path).subfiles.length > 0;
},
async isFile(path: string): Promise<boolean> {
return tree.exists(path);
},
};
}
export function myService(options: MyServiceSchema): Rule {
return async (tree: Tree) => {
const host = createHost(tree);
const {workspace} = await workspaces.readWorkspace('/', host);
// #enddocregion workspace
// #docregion project-info
const project = options.project != null ? workspace.projects.get(options.project) : null;
if (!project) {
throw new SchematicsException(`Invalid project name: ${options.project}`);
}
const projectType = project.extensions.projectType === 'application' ? 'app' : 'lib';
// #enddocregion project-info
// #docregion path
if (options.path === undefined) {
options.path = `${project.sourceRoot}/${projectType}`;
}
// #enddocregion path
// #docregion template
const templateSource = apply(url('./files'), [
applyTemplates({
classify: strings.classify,
dasherize: strings.dasherize,
name: options.name,
}),
move(normalize(options.path as string)),
]);
// #enddocregion template
// #docregion chain
return chain([mergeWith(templateSource)]);
// #enddocregion chain
// #docregion workspace
};
}
| {
"end_byte": 2248,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/files/__name@dasherize__.service.ts.template_0_246 | // #docregion template
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class <%= classify(name) %>Service {
constructor(private http: HttpClient) { }
} | {
"end_byte": 246,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/files/__name@dasherize__.service.ts.template"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/ng-add/schema.ts_0_73 | export interface Schema {
// Name of the project.
project: string;
}
| {
"end_byte": 73,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/ng-add/schema.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/ng-add/index.ts_0_393 | import {Rule} from '@angular-devkit/schematics';
import {addRootImport} from '@schematics/angular/utility';
import {Schema} from './schema';
export function ngAdd(options: Schema): Rule {
// Add an import `MyLibModule` from `my-lib` to the root of the user's project.
return addRootImport(
options.project,
({code, external}) => code`${external('MyLibModule', 'my-lib')}`,
);
}
| {
"end_byte": 393,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/ng-add/index.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/public_api.ts_0_155 | /*
* Public API Surface of my-lib
*/
export * from './lib/my-lib.service';
export * from './lib/my-lib.component';
export * from './lib/my-lib.module';
| {
"end_byte": 155,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/public_api.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.service.ts_0_111 | import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MyLibService {}
| {
"end_byte": 111,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.service.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.service.spec.ts_0_328 | import {TestBed} from '@angular/core/testing';
import {MyLibService} from './my-lib.service';
describe('MyLibService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: MyLibService = TestBed.inject(MyLibService);
expect(service).toBeTruthy();
});
});
| {
"end_byte": 328,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.service.spec.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.component.spec.ts_0_613 | import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {MyLibComponent} from './my-lib.component';
describe('MyLibComponent', () => {
let component: MyLibComponent;
let fixture: ComponentFixture<MyLibComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({declarations: [MyLibComponent]}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyLibComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| {
"end_byte": 613,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.component.spec.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.module.ts_0_213 | import {NgModule} from '@angular/core';
import {MyLibComponent} from './my-lib.component';
@NgModule({
declarations: [MyLibComponent],
imports: [],
exports: [MyLibComponent],
})
export class MyLibModule {}
| {
"end_byte": 213,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.module.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.component.ts_0_206 | import {Component} from '@angular/core';
@Component({
selector: 'lib-my-lib',
template: `
<p>
my-lib works!
</p>
`,
styles: [],
standalone: false,
})
export class MyLibComponent {}
| {
"end_byte": 206,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/projects/my-lib/src/lib/my-lib.component.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/src/index.html_0_308 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SchematicsForLibraries</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
| {
"end_byte": 308,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/src/index.html"
} |
angular/adev/src/content/examples/schematics-for-libraries/src/main.ts_0_214 | import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app/app.module';
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch((err) => console.error(err));
| {
"end_byte": 214,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/src/main.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/src/app/app.module.ts_0_292 | import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
| {
"end_byte": 292,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/src/app/app.module.ts"
} |
angular/adev/src/content/examples/schematics-for-libraries/src/app/app.component.ts_0_236 | import {Component} from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h2>Library Schematics</h2>
`,
styles: [],
standalone: false,
})
export class AppComponent {
title = 'schematics-for-libraries';
}
| {
"end_byte": 236,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/schematics-for-libraries/src/app/app.component.ts"
} |
angular/adev/src/content/examples/bootstrapping/BUILD.bazel_0_54 | package(default_visibility = ["//visibility:public"])
| {
"end_byte": 54,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/bootstrapping/BUILD.bazel"
} |
angular/adev/src/content/examples/bootstrapping/e2e/src/app.e2e-spec.ts_0_313 | import {AppPage} from './app.po';
describe('feature-modules App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display message saying app works', async () => {
await page.navigateTo();
expect(await page.getTitleText()).toEqual('app works!');
});
});
| {
"end_byte": 313,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/bootstrapping/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/bootstrapping/src/index.html_0_308 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NgmoduleDemo</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root>Loading...</app-root>
</body>
</html>
| {
"end_byte": 308,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/bootstrapping/src/index.html"
} |
angular/adev/src/content/examples/bootstrapping/src/main.ts_0_214 | import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app/app.module';
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch((err) => console.error(err));
| {
"end_byte": 214,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/bootstrapping/src/main.ts"
} |
angular/adev/src/content/examples/bootstrapping/src/app/app.component.html_0_25 | <h1>
{{ title }}
</h1>
| {
"end_byte": 25,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/bootstrapping/src/app/app.component.html"
} |
angular/adev/src/content/examples/bootstrapping/src/app/app.module.ts_0_729 | // #docplaster
// imports
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from '@angular/common/http';
import {AppComponent} from './app.component';
// #docregion directive-import
import {ItemDirective} from './item.directive';
// #enddocregion directive-import
// @NgModule decorator with its metadata
@NgModule({
// #docregion declarations
declarations: [AppComponent, ItemDirective],
// #enddocregion declarations
// #docregion imports
imports: [BrowserModule, FormsModule, HttpClientModule],
// #enddocregion imports
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
| {
"end_byte": 729,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/bootstrapping/src/app/app.module.ts"
} |
angular/adev/src/content/examples/bootstrapping/src/app/app.component.ts_0_234 | import {Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
standalone: false,
})
export class AppComponent {
title = 'app works!';
}
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/bootstrapping/src/app/app.component.ts"
} |
angular/adev/src/content/examples/bootstrapping/src/app/item.directive.ts_0_241 | // #docplaster
// #docregion directive
import {Directive} from '@angular/core';
@Directive({
selector: '[appItem]',
standalone: false,
})
export class ItemDirective {
// code goes here
constructor() {}
}
// #enddocregion directive
| {
"end_byte": 241,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/bootstrapping/src/app/item.directive.ts"
} |
angular/adev/src/content/examples/security/BUILD.bazel_0_260 | package(default_visibility = ["//visibility:public"])
exports_files([
"src/app/bypass-security.component.html",
"src/app/bypass-security.component.ts",
"src/app/inner-html-binding.component.html",
"src/app/inner-html-binding.component.ts",
])
| {
"end_byte": 260,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/BUILD.bazel"
} |
angular/adev/src/content/examples/security/e2e/src/app.e2e-spec.ts_0_1420 | import {browser, element, By} from 'protractor';
describe('Security E2E Tests', () => {
beforeAll(() => browser.get(''));
it('sanitizes innerHTML', async () => {
const interpolated = element(By.className('e2e-inner-html-interpolated'));
expect(await interpolated.getText()).toContain(
'Template <script>alert("0wned")</script> <b>Syntax</b>',
);
const bound = element(By.className('e2e-inner-html-bound'));
expect(await bound.getText()).toContain('Template Syntax');
const bold = element(By.css('.e2e-inner-html-bound b'));
expect(await bold.getText()).toContain('Syntax');
});
it('escapes untrusted URLs', async () => {
const untrustedUrl = element(By.className('e2e-dangerous-url'));
expect(await untrustedUrl.getAttribute('href')).toMatch(/^unsafe:javascript/);
});
it('binds trusted URLs', async () => {
const trustedUrl = element(By.className('e2e-trusted-url'));
expect(await trustedUrl.getAttribute('href')).toMatch(/^javascript:alert/);
});
it('escapes untrusted resource URLs', async () => {
const iframe = element(By.className('e2e-iframe-untrusted-src'));
expect(await iframe.getAttribute('src')).toBe('');
});
it('binds trusted resource URLs', async () => {
const iframe = element(By.className('e2e-iframe-trusted-src'));
expect(await iframe.getAttribute('src')).toMatch(/^https:\/\/www\.youtube\.com\//);
});
});
| {
"end_byte": 1420,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/security/src/index.html_0_290 | <!-- #docregion -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Angular Content Security</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>
| {
"end_byte": 290,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/src/index.html"
} |
angular/adev/src/content/examples/security/src/main.ts_0_275 | import {bootstrapApplication, provideProtractorTestingSupport} from '@angular/platform-browser';
import {AppComponent} from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [provideProtractorTestingSupport()],
}).catch((err) => console.error(err));
| {
"end_byte": 275,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/src/main.ts"
} |
angular/adev/src/content/examples/security/src/app/app.component.ts_0_496 | // #docregion
import {Component} from '@angular/core';
import {BypassSecurityComponent} from './bypass-security.component';
import {InnerHtmlBindingComponent} from './inner-html-binding.component';
@Component({
standalone: true,
selector: 'app-root',
template: `
<h1>Security</h1>
<app-inner-html-binding></app-inner-html-binding>
<app-bypass-security></app-bypass-security>
`,
imports: [BypassSecurityComponent, InnerHtmlBindingComponent],
})
export class AppComponent {}
| {
"end_byte": 496,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/src/app/app.component.ts"
} |
angular/adev/src/content/examples/security/src/app/inner-html-binding.component.html_0_230 | <!-- #docregion -->
<h3>Binding innerHTML</h3>
<p>Bound value:</p>
<p class="e2e-inner-html-interpolated">{{ htmlSnippet }}</p>
<p>Result of binding to innerHTML:</p>
<p class="e2e-inner-html-bound" [innerHTML]="htmlSnippet"></p>
| {
"end_byte": 230,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/src/app/inner-html-binding.component.html"
} |
angular/adev/src/content/examples/security/src/app/bypass-security.component.ts_0_1348 | // #docplaster
// #docregion
import {Component} from '@angular/core';
import {DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';
@Component({
standalone: true,
selector: 'app-bypass-security',
templateUrl: './bypass-security.component.html',
})
export class BypassSecurityComponent {
dangerousUrl: string;
trustedUrl: SafeUrl;
dangerousVideoUrl!: string;
videoUrl!: SafeResourceUrl;
// #docregion trust-url
constructor(private sanitizer: DomSanitizer) {
// javascript: URLs are dangerous if attacker controlled.
// Angular sanitizes them in data binding, but you can
// explicitly tell Angular to trust this value:
this.dangerousUrl = 'javascript:alert("Hi there")';
this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
// #enddocregion trust-url
this.updateVideoUrl('PUBnlbjZFAI');
}
// #docregion trust-video-url
updateVideoUrl(id: string) {
// Appending an ID to a YouTube URL is safe.
// Always make sure to construct SafeValue objects as
// close as possible to the input data so
// that it's easier to check if the value is safe.
this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id;
this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl);
}
// #enddocregion trust-video-url
}
| {
"end_byte": 1348,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/src/app/bypass-security.component.ts"
} |
angular/adev/src/content/examples/security/src/app/inner-html-binding.component.ts_0_384 | // #docregion
import {Component} from '@angular/core';
@Component({
standalone: true,
selector: 'app-inner-html-binding',
templateUrl: './inner-html-binding.component.html',
})
// #docregion class
export class InnerHtmlBindingComponent {
// For example, a user/attacker-controlled value from a URL.
htmlSnippet = 'Template <script>alert("0wned")</script> <b>Syntax</b>';
}
| {
"end_byte": 384,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/src/app/inner-html-binding.component.ts"
} |
angular/adev/src/content/examples/security/src/app/bypass-security.component.html_0_664 | <!--#docregion -->
<h3>Bypass Security Component</h3>
<!--#docregion URL -->
<h4>An untrusted URL:</h4>
<p><a class="e2e-dangerous-url" [href]="dangerousUrl">Click me</a></p>
<h4>A trusted URL:</h4>
<p><a class="e2e-trusted-url" [href]="trustedUrl">Click me</a></p>
<!--#enddocregion URL -->
<!--#docregion iframe -->
<h4>Resource URL:</h4>
<p>Showing: {{ dangerousVideoUrl }}</p>
<p>Trusted:</p>
<iframe class="e2e-iframe-trusted-src" width="640" height="390" [src]="videoUrl" title="trusted video url"></iframe>
<p>Untrusted:</p>
<iframe class="e2e-iframe-untrusted-src" width="640" height="390" [src]="dangerousVideoUrl" title="unTrusted video url"></iframe>
| {
"end_byte": 664,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/security/src/app/bypass-security.component.html"
} |
angular/adev/src/content/examples/form-validation/BUILD.bazel_0_480 | package(default_visibility = ["//visibility:public"])
exports_files([
"src/app/reactive/actor-form-reactive.component.1.ts",
"src/app/reactive/actor-form-reactive.component.2.ts",
"src/app/reactive/actor-form-reactive.component.html",
"src/app/shared/forbidden-name.directive.ts",
"src/app/shared/role.directive.ts",
"src/app/shared/unambiguous-role.directive.ts",
"src/app/template/actor-form-template.component.html",
"src/assets/forms.css",
])
| {
"end_byte": 480,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/BUILD.bazel"
} |
angular/adev/src/content/examples/form-validation/e2e/src/app.e2e-spec.ts_0_7542 | import {browser, element, by, protractor, ElementFinder, ElementArrayFinder} from 'protractor';
// THESE TESTS ARE INCOMPLETE
describe('Form Validation Tests', () => {
beforeAll(() => browser.get(''));
describe('Template-driven form', () => {
beforeAll(() => {
getPage('app-actor-form-template');
});
tests('Template-Driven Form');
bobTests();
asyncValidationTests();
crossValidationTests();
});
describe('Reactive form', () => {
beforeAll(() => {
getPage('app-actor-form-reactive');
});
tests('Reactive Form');
bobTests();
asyncValidationTests();
crossValidationTests();
});
});
//////////
const testName = 'Test Name';
let page: {
section: ElementFinder;
form: ElementFinder;
title: ElementFinder;
nameInput: ElementFinder;
roleInput: ElementFinder;
skillSelect: ElementFinder;
skillOption: ElementFinder;
errorMessages: ElementArrayFinder;
actorFormButtons: ElementArrayFinder;
actorSubmitted: ElementFinder;
roleErrors: ElementFinder;
crossValidationErrorMessage: ElementFinder;
};
function getPage(sectionTag: string) {
const section = element(by.css(sectionTag));
const buttons = section.all(by.css('button'));
page = {
section,
form: section.element(by.css('form')),
title: section.element(by.css('h2')),
nameInput: section.element(by.css('#name')),
roleInput: section.element(by.css('#role')),
skillSelect: section.element(by.css('#skill')),
skillOption: section.element(by.css('#skill option')),
errorMessages: section.all(by.css('div.alert')),
actorFormButtons: buttons,
actorSubmitted: section.element(by.css('.submitted-message')),
roleErrors: section.element(by.css('.role-errors')),
crossValidationErrorMessage: section.element(by.css('.cross-validation-error-message')),
};
}
function tests(title: string) {
it('should display correct title', async () => {
expect(await page.title.getText()).toContain(title);
});
it('should not display submitted message before submit', async () => {
expect(await page.actorSubmitted.isElementPresent(by.css('p'))).toBe(false);
});
it('should have form buttons', async () => {
expect(await page.actorFormButtons.count()).toEqual(2);
});
it('should have error at start', async () => {
await expectFormIsInvalid();
});
// it('showForm', () => {
// page.form.getInnerHtml().then(html => console.log(html));
// });
it('should have disabled submit button', async () => {
expect(await page.actorFormButtons.get(0).isEnabled()).toBe(false);
});
it('resetting name to valid name should clear errors', async () => {
const ele = page.nameInput;
expect(await ele.isPresent()).toBe(true, 'nameInput should exist');
await ele.clear();
await ele.sendKeys(testName);
await expectFormIsValid();
});
it('should produce "required" error after clearing name', async () => {
await page.nameInput.clear();
// await page.roleInput.click(); // to blur ... didn't work
await page.nameInput.sendKeys('x', protractor.Key.BACK_SPACE); // ugh!
expect(await page.form.getAttribute('class')).toMatch('ng-invalid');
expect(await page.errorMessages.get(0).getText()).toContain('required');
});
it('should produce "at least 4 characters" error when name="x"', async () => {
await page.nameInput.clear();
await page.nameInput.sendKeys('x'); // too short
await expectFormIsInvalid();
expect(await page.errorMessages.get(0).getText()).toContain('at least 4 characters');
});
it('resetting name to valid name again should clear errors', async () => {
await page.nameInput.sendKeys(testName);
await expectFormIsValid();
});
it('should have enabled submit button', async () => {
const submitBtn = page.actorFormButtons.get(0);
expect(await submitBtn.isEnabled()).toBe(true);
});
it('should hide form after submit', async () => {
await page.actorFormButtons.get(0).click();
expect(await page.actorFormButtons.get(0).isDisplayed()).toBe(false);
});
it('submitted form should be displayed', async () => {
expect(await page.actorSubmitted.isElementPresent(by.css('p'))).toBe(true);
});
it('submitted form should have new actor name', async () => {
expect(await page.actorSubmitted.getText()).toContain(testName);
});
it('clicking edit button should reveal form again', async () => {
const newFormBtn = page.actorSubmitted.element(by.css('button'));
await newFormBtn.click();
expect(await page.actorSubmitted.isElementPresent(by.css('p'))).toBe(
false,
'submitted hidden again',
);
expect(await page.title.isDisplayed()).toBe(true, 'can see form title');
});
}
async function expectFormIsValid() {
expect(await page.form.getAttribute('class')).toMatch('ng-valid');
}
async function expectFormIsInvalid() {
expect(await page.form.getAttribute('class')).toMatch('ng-invalid');
}
async function triggerRoleValidation() {
// role has updateOn set to 'blur', click outside of the input to trigger the blur event
await element(by.css('app-root')).click();
}
async function waitForAlterEgoValidation() {
// role async validation will be performed in 400ms
await browser.sleep(400);
}
function bobTests() {
const emsg = 'Name cannot be Bob.';
it('should produce "no bob" error after setting name to "Bobby"', async () => {
// Re-populate select element
await page.skillSelect.click();
await page.skillOption.click();
await page.nameInput.clear();
await page.nameInput.sendKeys('Bobby');
await expectFormIsInvalid();
expect(await page.errorMessages.get(0).getText()).toBe(emsg);
});
it('should be ok again with valid name', async () => {
await page.nameInput.clear();
await page.nameInput.sendKeys(testName);
await expectFormIsValid();
});
}
function asyncValidationTests() {
const emsg = 'Role is already taken.';
it(`should produce "${emsg}" error after setting role to Eric`, async () => {
await page.roleInput.clear();
await page.roleInput.sendKeys('Eric');
await triggerRoleValidation();
await waitForAlterEgoValidation();
await expectFormIsInvalid();
expect(await page.roleErrors.getText()).toBe(emsg);
});
it('should be ok again with different values', async () => {
await page.roleInput.clear();
await page.roleInput.sendKeys('John');
await triggerRoleValidation();
await waitForAlterEgoValidation();
await expectFormIsValid();
expect(await page.roleErrors.isPresent()).toBe(false);
});
}
function crossValidationTests() {
const emsg = 'Name cannot match role.';
it(`should produce "${emsg}" error after setting name and role to the same value`, async () => {
await page.nameInput.clear();
await page.nameInput.sendKeys('Romeo');
await page.roleInput.clear();
await page.roleInput.sendKeys('Romeo');
await triggerRoleValidation();
await waitForAlterEgoValidation();
await expectFormIsInvalid();
expect(await page.crossValidationErrorMessage.getText()).toBe(emsg);
});
it('should be ok again with different values', async () => {
await page.nameInput.clear();
await page.nameInput.sendKeys('Romeo');
await page.roleInput.clear();
await page.roleInput.sendKeys('Juliet');
await triggerRoleValidation();
await waitForAlterEgoValidation();
await expectFormIsValid();
expect(await page.crossValidationErrorMessage.isPresent()).toBe(false);
});
}
| {
"end_byte": 7542,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/form-validation/src/index.html_0_324 | <!DOCTYPE html>
<html lang="en">
<head>
<title>Hero Form with Validation</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/forms.css">
</head>
<body>
<app-root></app-root>
</body>
</html>
| {
"end_byte": 324,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/index.html"
} |
angular/adev/src/content/examples/form-validation/src/main.ts_0_228 | // #docregion
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app/app.module';
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch((err) => console.error(err));
| {
"end_byte": 228,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/main.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/app.module.ts_0_973 | // #docregion
import {NgModule} from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
import {ActorFormTemplateComponent} from './template/actor-form-template.component';
import {ActorFormReactiveComponent} from './reactive/actor-form-reactive.component';
import {ForbiddenValidatorDirective} from './shared/forbidden-name.directive';
import {UnambiguousRoleValidatorDirective} from './shared/unambiguous-role.directive';
import {UniqueRoleValidatorDirective} from './shared/role.directive';
@NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule],
declarations: [
AppComponent,
ActorFormTemplateComponent,
ActorFormReactiveComponent,
ForbiddenValidatorDirective,
UnambiguousRoleValidatorDirective,
UniqueRoleValidatorDirective,
],
bootstrap: [AppComponent],
})
export class AppModule {}
| {
"end_byte": 973,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/app.module.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/app.component.ts_0_292 | // #docregion
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
template: `<h1>Form validation example</h1>
<app-actor-form-template/>
<hr>
<app-actor-form-reactive/>`,
standalone: false,
})
export class AppComponent {}
| {
"end_byte": 292,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/app.component.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.2.ts_0_1625 | // #docplaster
// #docregion
import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {forbiddenNameValidator} from '../shared/forbidden-name.directive';
import {UniqueRoleValidator} from '../shared/role.directive';
@Component({
selector: 'app-actor-form-reactive',
templateUrl: './actor-form-reactive.component.html',
styleUrls: ['./actor-form-reactive.component.css'],
standalone: false,
})
export class HeroFormReactiveComponent implements OnInit {
skills = ['Method Acting', 'Singing', 'Dancing', 'Swordfighting'];
actor = {name: 'Tom Cruise', role: 'Romeo', skill: this.skills[3]};
actorForm!: FormGroup;
ngOnInit(): void {
// #docregion async-validator-usage
const roleControl = new FormControl('', {
asyncValidators: [this.roleValidator.validate.bind(this.roleValidator)],
updateOn: 'blur',
});
// #enddocregion async-validator-usage
roleControl.setValue(this.actor.role);
this.actorForm = new FormGroup({
name: new FormControl(this.actor.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i),
]),
role: roleControl,
skill: new FormControl(this.actor.skill, Validators.required),
});
}
get name() {
return this.actorForm.get('name');
}
get skill() {
return this.actorForm.get('skill');
}
get role() {
return this.actorForm.get('role');
}
// #docregion async-validator-inject
constructor(private roleValidator: UniqueRoleValidator) {}
// #enddocregion async-validator-inject
}
| {
"end_byte": 1625,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.2.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.ts_0_1600 | // #docregion
import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {forbiddenNameValidator} from '../shared/forbidden-name.directive';
import {unambiguousRoleValidator} from '../shared/identity-revealed.directive';
import {UniqueRoleValidator} from '../shared/role.directive';
@Component({
selector: 'app-actor-form-reactive',
templateUrl: './actor-form-reactive.component.html',
styleUrls: ['./actor-form-reactive.component.css'],
standalone: false,
})
export class ActorFormReactiveComponent implements OnInit {
skills = ['Method Acting', 'Singing', 'Dancing', 'Swordfighting'];
actor = {name: 'Tom Cruise', role: 'Romeo', skill: this.skills[3]};
actorForm!: FormGroup;
ngOnInit(): void {
this.actorForm = new FormGroup(
{
name: new FormControl(this.actor.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i),
]),
role: new FormControl(this.actor.role, {
asyncValidators: [this.roleValidator.validate.bind(this.roleValidator)],
updateOn: 'blur',
}),
skill: new FormControl(this.actor.skill, Validators.required),
},
{validators: unambiguousRoleValidator},
); // <-- add custom validator at the FormGroup level
}
get name() {
return this.actorForm.get('name')!;
}
get skill() {
return this.actorForm.get('skill')!;
}
get role() {
return this.actorForm.get('role')!;
}
constructor(private roleValidator: UniqueRoleValidator) {}
}
| {
"end_byte": 1600,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.html_1_2909 | <!-- #docregion -->
<div class="container">
<h2>Reactive Form</h2>
<form [formGroup]="actorForm" #formDir="ngForm">
<div [hidden]="formDir.submitted">
<div class="cross-validation" [class.cross-validation-error]="actorForm.hasError('unambiguousRole') && (actorForm.touched || actorForm.dirty)">
<div class="form-group">
<label for="name">Name</label>
<!-- #docregion name-with-error-msg -->
<input type="text" id="name" class="form-control"
formControlName="name" required>
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.hasError('required')">
Name is required.
</div>
<div *ngIf="name.hasError('minlength')">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.hasError('forbiddenName')">
Name cannot be Bob.
</div>
</div>
<!-- #enddocregion name-with-error-msg -->
</div>
<div class="form-group">
<label for="role">Role</label>
<input type="text" id="role" class="form-control"
formControlName="role">
<div *ngIf="role.pending">Validating...</div>
<div *ngIf="role.invalid" class="alert alert-danger role-errors">
<div *ngIf="role.hasError('uniqueRole')">
Role is already taken.
</div>
</div>
</div>
<!-- #docregion cross-validation-error-message -->
<div *ngIf="actorForm.hasError('unambiguousRole') && (actorForm.touched || actorForm.dirty)" class="cross-validation-error-message alert alert-danger">
Name cannot match role or audiences will be confused.
</div>
<!-- #enddocregion cross-validation-error-message -->
</div>
<div class="form-group">
<label for="skill">Skill</label>
<select id="skill" class="form-control"
formControlName="skill" required>
<option *ngFor="let skill of skills" [value]="skill">{{ skill }}</option>
</select>
<div *ngIf="skill.invalid && skill.touched" class="alert alert-danger">
<div *ngIf="skill.hasError('required')">Skill is required.</div>
</div>
</div>
<p>Complete the form to enable the Submit button.</p>
<button type="submit"
class="btn btn-default"
[disabled]="actorForm.invalid">Submit</button>
<button type="button" class="btn btn-default"
(click)="formDir.resetForm({})">Reset</button>
</div>
</form>
<div class="submitted-message" *ngIf="formDir.submitted">
<p>You've submitted your actor, {{ actorForm.value.name }}!</p>
<button type="button" (click)="formDir.resetForm({})">Add new actor</button>
</div>
</div>
| {
"end_byte": 2909,
"start_byte": 1,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.html"
} |
angular/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.1.ts_0_1297 | // #docplaster
// #docregion
import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {forbiddenNameValidator} from '../shared/forbidden-name.directive';
@Component({
selector: 'app-actor-form-reactive',
templateUrl: './actor-form-reactive.component.html',
styleUrls: ['./actor-form-reactive.component.css'],
standalone: false,
})
export class HeroFormReactiveComponent implements OnInit {
skills = ['Method Acting', 'Singing', 'Dancing', 'Swordfighting'];
actor = {name: 'Tom Cruise', role: 'Romeo', skill: this.skills[3]};
actorForm!: FormGroup;
// #docregion form-group
ngOnInit(): void {
// #docregion custom-validator
this.actorForm = new FormGroup({
name: new FormControl(this.actor.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i), // <-- Here's how you pass in the custom validator.
]),
role: new FormControl(this.actor.role),
skill: new FormControl(this.actor.skill, Validators.required),
});
// #enddocregion custom-validator
}
get name() {
return this.actorForm.get('name');
}
get skill() {
return this.actorForm.get('skill');
}
// #enddocregion form-group
}
// #enddocregion
| {
"end_byte": 1297,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.1.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.css_0_64 | .cross-validation-error input {
border-left: 5px solid red;
}
| {
"end_byte": 64,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.css"
} |
angular/adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.html_1_3327 | <!-- #docregion -->
<div>
<h2>Template-Driven Form</h2>
<!-- #docregion cross-validation-register-validator -->
<form #actorForm="ngForm" appUnambiguousRole>
<!-- #enddocregion cross-validation-register-validator -->
<div [hidden]="actorForm.submitted">
<div class="cross-validation" [class.cross-validation-error]="actorForm.hasError('unambiguousRole') && (actorForm.touched || actorForm.dirty)">
<div class="form-group">
<label for="name">Name</label>
<!-- #docregion name-with-error-msg -->
<!-- #docregion name-input -->
<input type="text" id="name" name="name" class="form-control"
required minlength="4" appForbiddenName="bob"
[(ngModel)]="actor.name" #name="ngModel">
<!-- #enddocregion name-input -->
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert">
<div *ngIf="name.hasError('required')">
Name is required.
</div>
<div *ngIf="name.hasError('minlength')">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.hasError('forbiddenName')">
Name cannot be Bob.
</div>
</div>
<!-- #enddocregion name-with-error-msg -->
</div>
<div class="form-group">
<label for="role">Role</label>
<!-- #docregion role-input -->
<input type="text"
id="role"
name="role"
#role="ngModel"
[(ngModel)]="actor.role"
[ngModelOptions]="{ updateOn: 'blur' }"
appUniqueRole>
<!-- #enddocregion role-input -->
<div *ngIf="role.pending">Validating...</div>
<div *ngIf="role.invalid" class="alert role-errors">
<div *ngIf="role.hasError('uniqueRole')">
Role is already taken.
</div>
</div>
</div>
<!-- #docregion cross-validation-error-message -->
<div *ngIf="actorForm.hasError('unambiguousRole') && (actorForm.touched || actorForm.dirty)" class="cross-validation-error-message alert">
Name cannot match role.
</div>
<!-- #enddocregion cross-validation-error-message -->
</div>
<div class="form-group">
<label for="skill">Skill</label>
<select id="skill"
name="skill"
required [(ngModel)]="actor.skill"
#skill="ngModel">
<option *ngFor="let skill of skills" [value]="skill">{{ skill }}</option>
</select>
<div *ngIf="skill.errors && skill.touched" class="alert">
<div *ngIf="skill.errors['required']">Power is required.</div>
</div>
</div>
<p>Complete the form to enable the Submit button.</p>
<button type="submit"
[disabled]="actorForm.invalid">Submit</button>
<button type="button"
(click)="actorForm.resetForm({})">Reset</button>
</div>
<div class="submitted-message" *ngIf="actorForm.submitted">
<p>You've submitted your actor, {{ actorForm.value.name }}!</p>
<button type="button" (click)="actorForm.resetForm({})">Add new actor</button>
</div>
</form>
</div>
| {
"end_byte": 3327,
"start_byte": 1,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.html"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.