_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular/adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.ts_0_411 | import {Component} from '@angular/core';
@Component({
selector: 'app-actor-form-template',
templateUrl: './actor-form-template.component.html',
styleUrls: ['./actor-form-template.component.css'],
standalone: false,
})
export class ActorFormTemplateComponent {
skills = ['Method Acting', 'Singing', 'Dancing', 'Swordfighting'];
actor = {name: 'Tom Cruise', role: 'Romeo', skill: this.skills[3]};
}
| {
"end_byte": 411,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.css_0_85 | /* #docregion */
.cross-validation-error input {
border-left: 5px solid #a94442;
}
| {
"end_byte": 85,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.css"
} |
angular/adev/src/content/examples/form-validation/src/app/shared/unambiguous-role.ts_0_1044 | // #docregion
import {Directive} from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
ValidatorFn,
} from '@angular/forms';
// #docregion cross-validation-validator
/** An actor's name can't match the actor's role */
export const unambiguousRoleValidator: ValidatorFn = (
control: AbstractControl,
): ValidationErrors | null => {
const name = control.get('name');
const role = control.get('role');
return name && role && name.value === role.value ? {identityRevealed: true} : null;
};
// #enddocregion cross-validation-validator
// #docregion cross-validation-directive
@Directive({
selector: '[appUnambiguousRole]',
providers: [
{provide: NG_VALIDATORS, useExisting: UnambiguousRoleValidatorDirective, multi: true},
],
standalone: false,
})
export class UnambiguousRoleValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
return unambiguousRoleValidator(control);
}
}
// #enddocregion cross-validation-directive
| {
"end_byte": 1044,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/shared/unambiguous-role.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/shared/unambiguous-role.directive.ts_0_1043 | // #docregion
import {Directive} from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
ValidatorFn,
} from '@angular/forms';
// #docregion cross-validation-validator
/** An actor's name can't match the actor's role */
export const unambiguousRoleValidator: ValidatorFn = (
control: AbstractControl,
): ValidationErrors | null => {
const name = control.get('name');
const role = control.get('role');
return name && role && name.value === role.value ? {unambiguousRole: true} : null;
};
// #enddocregion cross-validation-validator
// #docregion cross-validation-directive
@Directive({
selector: '[appUnambiguousRole]',
providers: [
{provide: NG_VALIDATORS, useExisting: UnambiguousRoleValidatorDirective, multi: true},
],
standalone: false,
})
export class UnambiguousRoleValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
return unambiguousRoleValidator(control);
}
}
// #enddocregion cross-validation-directive
| {
"end_byte": 1043,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/shared/unambiguous-role.directive.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/shared/forbidden-name.directive.ts_0_1134 | // #docregion
import {Directive, Input} from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
ValidatorFn,
} from '@angular/forms';
// #docregion custom-validator
/** An actor's name can't match the given regular expression */
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? {forbiddenName: {value: control.value}} : null;
};
}
// #enddocregion custom-validator
// #docregion directive
@Directive({
selector: '[appForbiddenName]',
// #docregion directive-providers
providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}],
standalone: false,
})
export class ForbiddenValidatorDirective implements Validator {
@Input('appForbiddenName') forbiddenName = '';
validate(control: AbstractControl): ValidationErrors | null {
return this.forbiddenName
? forbiddenNameValidator(new RegExp(this.forbiddenName, 'i'))(control)
: null;
}
}
// #enddocregion directive
| {
"end_byte": 1134,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/shared/forbidden-name.directive.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/shared/actors.service.ts_0_379 | import {Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {delay} from 'rxjs/operators';
const ROLES = ['Hamlet', 'Ophelia', 'Romeo', 'Juliet'];
@Injectable({providedIn: 'root'})
export class ActorsService {
isRoleTaken(role: string): Observable<boolean> {
const isTaken = ROLES.includes(role);
return of(isTaken).pipe(delay(400));
}
}
| {
"end_byte": 379,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/shared/actors.service.ts"
} |
angular/adev/src/content/examples/form-validation/src/app/shared/role.directive.ts_0_1338 | import {Directive, forwardRef, Injectable} from '@angular/core';
import {
AsyncValidator,
AbstractControl,
NG_ASYNC_VALIDATORS,
ValidationErrors,
} from '@angular/forms';
import {catchError, map} from 'rxjs/operators';
import {ActorsService} from './actors.service';
import {Observable, of} from 'rxjs';
// #docregion async-validator
@Injectable({providedIn: 'root'})
export class UniqueRoleValidator implements AsyncValidator {
constructor(private actorsService: ActorsService) {}
validate(control: AbstractControl): Observable<ValidationErrors | null> {
return this.actorsService.isRoleTaken(control.value).pipe(
map((isTaken) => (isTaken ? {uniqueRole: true} : null)),
catchError(() => of(null)),
);
}
}
// #enddocregion async-validator
// #docregion async-validator-directive
@Directive({
selector: '[appUniqueRole]',
providers: [
{
provide: NG_ASYNC_VALIDATORS,
useExisting: forwardRef(() => UniqueRoleValidatorDirective),
multi: true,
},
],
standalone: false,
})
export class UniqueRoleValidatorDirective implements AsyncValidator {
constructor(private validator: UniqueRoleValidator) {}
validate(control: AbstractControl): Observable<ValidationErrors | null> {
return this.validator.validate(control);
}
}
// #enddocregion async-validator-directive
| {
"end_byte": 1338,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/app/shared/role.directive.ts"
} |
angular/adev/src/content/examples/form-validation/src/assets/forms.css_1_405 | .ng-valid[required], .ng-valid.required {
border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}
.alert div {
background-color: #fed3d3;
color: #820000;
padding: 1rem;
margin-bottom: 1rem;
}
.form-group {
margin-bottom: 1rem;
}
label {
display: block;
margin-bottom: .5rem;
}
select {
width: 100%;
padding: .5rem;
}
| {
"end_byte": 405,
"start_byte": 1,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/form-validation/src/assets/forms.css"
} |
angular/adev/src/content/examples/inputs-outputs/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/inputs-outputs/BUILD.bazel"
} |
angular/adev/src/content/examples/inputs-outputs/e2e/src/app.e2e-spec.ts_0_2103 | import {browser, element, by, logging, ExpectedConditions as EC} from 'protractor';
describe('Inputs and Outputs', () => {
beforeEach(() => browser.get(''));
// helper function used to test what's logged to the console
async function logChecker(contents: string) {
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
const messages = logs.filter(({message}) => message.indexOf(contents) !== -1);
expect(messages.length).toBeGreaterThan(0);
}
it('should have title Inputs and Outputs', async () => {
const title = element.all(by.css('h1')).get(0);
expect(await title.getText()).toEqual('Inputs and Outputs');
});
it('should add 123 to the parent list', async () => {
const addToParentButton = element.all(by.css('button')).get(0);
const addToListInput = element.all(by.css('input')).get(0);
const addedItem = element.all(by.css('li')).get(4);
// Wait for an <li> to be present before sending keys to the input.
await browser.wait(EC.presenceOf(element.all(by.css('li')).get(0)), 5000);
await addToListInput.sendKeys('123');
await addToParentButton.click();
expect(await addedItem.getText()).toEqual('123');
});
it('should delete item', async () => {
const deleteButton = element.all(by.css('button')).get(1);
const contents = 'Child';
await deleteButton.click();
await logChecker(contents);
});
it('should log buy the item', async () => {
const buyButton = element.all(by.css('button')).get(2);
const contents = 'Child';
await buyButton.click();
await logChecker(contents);
});
it('should save item for later', async () => {
const saveButton = element.all(by.css('button')).get(3);
const contents = 'Child';
await saveButton.click();
await logChecker(contents);
});
it('should add item to wishlist', async () => {
const addToParentButton = element.all(by.css('button')).get(4);
const addedItem = element.all(by.css('li')).get(6);
await addToParentButton.click();
expect(await addedItem.getText()).toEqual('Television');
});
});
| {
"end_byte": 2103,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/inputs-outputs/src/index.html_0_304 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inputs and Outputs</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": 304,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/index.html"
} |
angular/adev/src/content/examples/inputs-outputs/src/main.ts_0_278 | import {bootstrapApplication, provideProtractorTestingSupport} from '@angular/platform-browser';
import {AppComponent} from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [
provideProtractorTestingSupport(), // essential for e2e testing
],
});
| {
"end_byte": 278,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/main.ts"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/app.component.html_0_1601 | <h1>Inputs and Outputs</h1>
<!-- #docregion input-parent -->
<app-item-detail [item]="currentItem"></app-item-detail>
<!-- #enddocregion input-parent -->
<!-- #docregion input-parent-metadata -->
<app-item-detail-metadata [item]="currentItem" [itemAvailability]="true"></app-item-detail-metadata>
<!-- #enddocregion input-parent-metadata -->
<hr>
<!-- #docregion output-parent -->
<app-item-output (newItemEvent)="addItem($event)"></app-item-output>
<!-- #enddocregion output-parent -->
<h3>Parent component receiving value via @Output()</h3>
<ul>
@for (item of items; track item) {
<li>{{ item }}</li>
}
</ul>
<hr>
<h2>Input and Output together</h2>
<p>Open the console to see the EventEmitter at work when you click Delete.</p>
<!-- #docregion together -->
<app-input-output
[item]="currentItem"
(deleteRequest)="crossOffItem($event)">
</app-input-output>
<!-- #enddocregion together -->
<hr>
<h2>Input and Output in the component class metadata</h2>
<p>Open the console to see the EventEmitter at work when you click Buy.</p>
<app-in-the-metadata
[clearanceItem]="lastChanceItem"
(buyEvent)="buyClearanceItem($event)">
</app-in-the-metadata>
<hr>
<h2>Aliasing Inputs and Outputs</h2>
<p>See aliasing.component.ts for aliases and the console for the EventEmitter console logs.</p>
<app-aliasing
[saveForLaterItem]="currentItem"
[wishListItem]="currentItem"
(saveForLaterEvent)="saveForLater($event)"
(wishEvent)="addToWishList($event)">
</app-aliasing>
<h2>Wishlist:</h2>
<ul>
@for (wish of wishlist; track wish) {
<li>{{ wish }}</li>
}
</ul>
| {
"end_byte": 1601,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/app.component.html"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/item-detail.component.html_0_169 | <h2>Child component with @Input()</h2>
<!-- #docregion property-in-template -->
<p>
Today's item: {{ item }}
</p>
<!-- #enddocregion property-in-template -->
| {
"end_byte": 169,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/item-detail.component.html"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/item-details-metadata.component.ts_0_1074 | // #docplaster
// #docregion use-input-metadata-required
import {Component, Input} from '@angular/core'; // First, import Input
// #enddocregion use-input-metadata-required
// #docregion use-input-metadata-boolean-transform
import {booleanAttribute} from '@angular/core'; // First, import booleanAttribute
// #enddocregion use-input-metadata-boolean-transform
@Component({
standalone: true,
selector: 'app-item-detail-metadata',
template: `
<h2>Child component with @Input() metadata configurations</h2>
<p>
Today's item: {{item}}
Item's Availability: {{itemAvailability}}
</p>
`,
})
export class ItemDetailMetadataComponent {
// #docregion use-input-metadata-required
@Input({required: true}) item!: string; // Second, decorate the property with required metadata
// #enddocregion use-input-metadata-required
// #docregion use-input-metadata-boolean-transform
@Input({transform: booleanAttribute}) itemAvailability!: boolean; // Second, decorate the property with transform
// #enddocregion use-input-metadata-boolean-transform
}
| {
"end_byte": 1074,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/item-details-metadata.component.ts"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/in-the-metadata.component.ts_0_677 | /* eslint-disable @angular-eslint/no-inputs-metadata-property, @angular-eslint/no-outputs-metadata-property */
import {Component, EventEmitter} from '@angular/core';
@Component({
standalone: true,
selector: 'app-in-the-metadata',
template: `
<p>Latest clearance item: {{clearanceItem}}</p>
<button type="button" (click)="buyIt()"> Buy it with an Output!</button>
`,
inputs: ['clearanceItem'],
outputs: ['buyEvent'],
})
export class InTheMetadataComponent {
buyEvent = new EventEmitter<string>();
clearanceItem = '';
buyIt() {
console.warn('Child says: emitting buyEvent with', this.clearanceItem);
this.buyEvent.emit(this.clearanceItem);
}
}
| {
"end_byte": 677,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/in-the-metadata.component.ts"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/item-output.component.html_0_295 | <h2>Child component with @Output()</h2>
<!-- #docregion child-output -->
<label for="item-input">Add an item:</label>
<input type="text" id="item-input" #newItem>
<button type="button" (click)="addNewItem(newItem.value)">Add to parent's list</button>
<!-- #enddocregion child-output -->
| {
"end_byte": 295,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/item-output.component.html"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/app.component.ts_0_1841 | // #docplaster
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
import {AliasingComponent} from './aliasing.component';
import {InputOutputComponent} from './input-output.component';
import {InTheMetadataComponent} from './in-the-metadata.component';
import {ItemDetailComponent} from './item-detail.component';
import {ItemDetailMetadataComponent} from './item-details-metadata.component';
import {ItemOutputComponent} from './item-output.component';
@Component({
standalone: true,
selector: 'app-root',
templateUrl: './app.component.html',
imports: [
AliasingComponent,
InputOutputComponent,
InTheMetadataComponent,
ItemDetailComponent,
ItemDetailMetadataComponent,
ItemOutputComponent,
NgFor,
],
})
// #docregion parent-property
// #docregion add-new-item
export class AppComponent {
// #enddocregion add-new-item
currentItem = 'Television';
// #enddocregion parent-property
lastChanceItem = 'Beanbag';
// #docregion add-new-item
items = ['item1', 'item2', 'item3', 'item4'];
// #enddocregion add-new-item
wishlist = ['Drone', 'Computer'];
// #docregion add-new-item
addItem(newItem: string) {
this.items.push(newItem);
}
// #enddocregion add-new-item
crossOffItem(item: string) {
console.warn(`Parent says: crossing off ${item}.`);
}
buyClearanceItem(item: string) {
console.warn(`Parent says: buying ${item}.`);
}
saveForLater(item: string) {
console.warn(`Parent says: saving ${item} for later.`);
}
addToWishList(wish: string) {
console.warn(`Parent says: adding ${this.currentItem} to your wishlist.`);
this.wishlist.push(wish);
console.warn(this.wishlist);
}
// #docregion add-new-item
// #docregion parent-property
}
// #enddocregion add-new-item
// #enddocregion parent-property
| {
"end_byte": 1841,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/app.component.ts"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/item-output.component.ts_0_467 | import {Component, Output, EventEmitter} from '@angular/core';
@Component({
standalone: true,
selector: 'app-item-output',
templateUrl: './item-output.component.html',
})
// #docregion item-output-class
export class ItemOutputComponent {
// #docregion item-output
@Output() newItemEvent = new EventEmitter<string>();
// #enddocregion item-output
addNewItem(value: string) {
this.newItemEvent.emit(value);
}
}
// #enddocregion item-output-class
| {
"end_byte": 467,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/item-output.component.ts"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/aliasing.component.ts_0_1265 | /* eslint-disable @angular-eslint/no-input-rename,
@angular-eslint/no-inputs-metadata-property,
@angular-eslint/no-output-rename,
@angular-eslint/no-outputs-metadata-property */
import {Component, EventEmitter, Input, Output} from '@angular/core';
@Component({
standalone: true,
selector: 'app-aliasing',
template: `
<p>Save for later item: {{input1}}</p>
<button type="button" (click)="saveIt()"> Save for later</button>
<p>Item for wishlist: {{input2}}</p>
<button type="button" (click)="wishForIt()"> Add to wishlist</button>
`,
inputs: ['input1: saveForLaterItem'], // propertyName:alias
outputs: ['outputEvent1: saveForLaterEvent'],
})
export class AliasingComponent {
input1 = '';
outputEvent1: EventEmitter<string> = new EventEmitter<string>();
@Input('wishListItem') input2 = ''; // @Input(alias)
@Output('wishEvent') outputEvent2 = new EventEmitter<string>(); // @Output(alias) propertyName = ...
saveIt() {
console.warn('Child says: emitting outputEvent1 with', this.input1);
this.outputEvent1.emit(this.input1);
}
wishForIt() {
console.warn('Child says: emitting outputEvent2', this.input2);
this.outputEvent2.emit(this.input2);
}
}
| {
"end_byte": 1265,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/aliasing.component.ts"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/input-output.component.ts_0_635 | import {Component, Input, Output, EventEmitter} from '@angular/core';
@Component({
standalone: true,
selector: 'app-input-output',
template: `
<p [style.text-decoration]="lineThrough">Item: {{item}}</p>
<button type="button" (click)="delete()">Delete item with an Output!</button>
`,
})
export class InputOutputComponent {
@Input() item = '';
@Output() deleteRequest = new EventEmitter<string>();
lineThrough = '';
delete() {
console.warn('Child says: emitting item deleteRequest with', this.item);
this.deleteRequest.emit(this.item);
this.lineThrough = this.lineThrough ? '' : 'line-through';
}
}
| {
"end_byte": 635,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/input-output.component.ts"
} |
angular/adev/src/content/examples/inputs-outputs/src/app/item-detail.component.ts_0_402 | // #docplaster
// #docregion use-input
import {Component, Input} from '@angular/core'; // First, import Input
// #enddocregion use-input
@Component({
standalone: true,
selector: 'app-item-detail',
templateUrl: './item-detail.component.html',
})
// #docregion use-input
export class ItemDetailComponent {
@Input() item = ''; // decorate the property with @Input()
}
// #enddocregion use-input
| {
"end_byte": 402,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/inputs-outputs/src/app/item-detail.component.ts"
} |
angular/adev/src/content/examples/angular-linker-plugin/webpack.config.mjs_0_560 | // #docplaster ...
// #docregion webpack-config
import linkerPlugin from '@angular/compiler-cli/linker/babel';
export default {
// #enddocregion webpack-config
// #docregion webpack-config
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: 'babel-loader',
options: {
plugins: [linkerPlugin],
compact: false,
cacheDirectory: true,
}
}
}
]
}
// #enddocregion webpack-config
// #docregion webpack-config
}
// #enddocregion webpack-config
| {
"end_byte": 560,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/angular-linker-plugin/webpack.config.mjs"
} |
angular/adev/src/content/examples/angular-linker-plugin/BUILD.bazel_0_27 | exports_files(glob(["*"]))
| {
"end_byte": 27,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/angular-linker-plugin/BUILD.bazel"
} |
angular/adev/src/content/examples/setup/non-essential-files.txt_0_164 | .git
.gitignore
.travis.yml
*.spec*.ts
CHANGELOG.md
e2e
favicon.ico
karma.conf.js
karma-test-shim.js
LICENSE
non-essential-files.txt
protractor.config.js
README.md
| {
"end_byte": 164,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/setup/non-essential-files.txt"
} |
angular/adev/src/content/examples/setup/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/setup/BUILD.bazel"
} |
angular/adev/src/content/examples/setup/e2e/src/app.e2e-spec.ts_0_304 | import {browser, element, by} from 'protractor';
describe('QuickStart E2E Tests', () => {
const expectedMsg = 'Hello Angular';
beforeEach(() => browser.get(''));
it(`should display: ${expectedMsg}`, async () => {
expect(await element(by.css('h1')).getText()).toEqual(expectedMsg);
});
});
| {
"end_byte": 304,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/setup/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/setup/src/index.html_0_732 | <!DOCTYPE html>
<html lang="en">
<head>
<title>Angular Quickstart Seed</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfills -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/bundles/zone.umd.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<app-root><!-- content managed by Angular --></app-root>
</body>
</html>
| {
"end_byte": 732,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/setup/src/index.html"
} |
angular/adev/src/content/examples/setup/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/setup/src/main.ts"
} |
angular/adev/src/content/examples/setup/src/systemjs.config.extras.js_0_209 | /**
* Add barrels and stuff
* Adjust as necessary for your application needs.
*/
// (function (global) {
// System.config({
// packages: {
// // add packages here
// }
// });
// })(this);
| {
"end_byte": 209,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/setup/src/systemjs.config.extras.js"
} |
angular/adev/src/content/examples/setup/src/app/app.component.spec.ts_0_928 | import {DebugElement} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {AppComponent} from './app.component';
describe('AppComponent', () => {
let de: DebugElement;
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({declarations: [AppComponent]}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('h1'));
});
it('should create component', () => expect(comp).toBeDefined());
it('should have expected <h1> text', () => {
fixture.detectChanges();
const h1 = de.nativeElement;
expect(h1.textContent).toMatch(/angular/i, '<h1> should say something about "Angular"');
});
});
| {
"end_byte": 928,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/setup/src/app/app.component.spec.ts"
} |
angular/adev/src/content/examples/setup/src/app/app.module.ts_0_288 | // #docregion
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
| {
"end_byte": 288,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/setup/src/app/app.module.ts"
} |
angular/adev/src/content/examples/setup/src/app/app.component.ts_0_206 | // #docregion
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
template: '<h1>Hello {{name}}</h1>',
standalone: false,
})
export class AppComponent {
name = 'Angular';
}
| {
"end_byte": 206,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/setup/src/app/app.component.ts"
} |
angular/adev/src/content/examples/forms-overview/BUILD.bazel_0_352 | package(default_visibility = ["//visibility:public"])
exports_files([
"src/app/reactive/favorite-color/favorite-color.component.spec.ts",
"src/app/reactive/favorite-color/favorite-color.component.ts",
"src/app/template/favorite-color/favorite-color.component.spec.ts",
"src/app/template/favorite-color/favorite-color.component.ts",
])
| {
"end_byte": 352,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/BUILD.bazel"
} |
angular/adev/src/content/examples/forms-overview/e2e/src/app.e2e-spec.ts_0_299 | import {AppPage} from './app.po';
describe('forms-overview App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display a title', async () => {
await page.navigateTo();
expect(await page.getTitleText()).toEqual('Forms Overview');
});
});
| {
"end_byte": 299,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/forms-overview/src/index.html_0_300 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Forms Overview</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": 300,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/index.html"
} |
angular/adev/src/content/examples/forms-overview/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/forms-overview/src/main.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/app.component.html_0_258 | <!--The content below is only a placeholder and can be replaced.-->
<h1>Forms Overview</h1>
<h2>Reactive</h2>
<app-reactive-favorite-color></app-reactive-favorite-color>
<h2>Template-Driven</h2>
<app-template-favorite-color></app-template-favorite-color> | {
"end_byte": 258,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/app.component.html"
} |
angular/adev/src/content/examples/forms-overview/src/app/app.component.spec.ts_0_935 | import {TestBed, waitForAsync} from '@angular/core/testing';
import {AppComponent} from './app.component';
import {ReactiveModule} from './reactive/reactive.module';
import {TemplateModule} from './template/template.module';
describe('AppComponent', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [ReactiveModule, TemplateModule],
declarations: [AppComponent],
}).compileComponents();
}));
it('should create the app', waitForAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
}));
it('should render title', waitForAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Forms Overview');
}));
});
| {
"end_byte": 935,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/app.component.spec.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/app.module.ts_0_425 | import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
import {ReactiveModule} from './reactive/reactive.module';
import {TemplateModule} from './template/template.module';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, ReactiveModule, TemplateModule],
bootstrap: [AppComponent],
})
export class AppModule {}
| {
"end_byte": 425,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/app.module.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/app.component.ts_0_235 | import {Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
standalone: false,
})
export class AppComponent {
title = 'forms-intro';
}
| {
"end_byte": 235,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/app.component.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/reactive/reactive.module.ts_0_394 | import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {ReactiveFormsModule} from '@angular/forms';
import {FavoriteColorComponent} from './favorite-color/favorite-color.component';
@NgModule({
imports: [CommonModule, ReactiveFormsModule],
declarations: [FavoriteColorComponent],
exports: [FavoriteColorComponent],
})
export class ReactiveModule {}
| {
"end_byte": 394,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/reactive/reactive.module.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/reactive/favorite-color/favorite-color.component.ts_0_348 | import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
@Component({
selector: 'app-reactive-favorite-color',
template: `
Favorite Color: <input type="text" [formControl]="favoriteColorControl">
`,
standalone: false,
})
export class FavoriteColorComponent {
favoriteColorControl = new FormControl('');
}
| {
"end_byte": 348,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/reactive/favorite-color/favorite-color.component.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/reactive/favorite-color/favorite-color.component.spec.ts_0_1483 | import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {ReactiveFormsModule} from '@angular/forms';
import {createNewEvent} from '../../shared/utils';
import {FavoriteColorComponent} from './favorite-color.component';
describe('Favorite Color Component', () => {
let component: FavoriteColorComponent;
let fixture: ComponentFixture<FavoriteColorComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule],
declarations: [FavoriteColorComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FavoriteColorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
// #docregion view-to-model
it('should update the value of the input field', () => {
const input = fixture.nativeElement.querySelector('input');
const event = createNewEvent('input');
input.value = 'Red';
input.dispatchEvent(event);
expect(fixture.componentInstance.favoriteColorControl.value).toEqual('Red');
});
// #enddocregion view-to-model
// #docregion model-to-view
it('should update the value in the control', () => {
component.favoriteColorControl.setValue('Blue');
const input = fixture.nativeElement.querySelector('input');
expect(input.value).toBe('Blue');
});
// #enddocregion model-to-view
});
| {
"end_byte": 1483,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/reactive/favorite-color/favorite-color.component.spec.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/template/template.module.ts_0_378 | import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {FavoriteColorComponent} from './favorite-color/favorite-color.component';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [FavoriteColorComponent],
exports: [FavoriteColorComponent],
})
export class TemplateModule {}
| {
"end_byte": 378,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/template/template.module.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/template/favorite-color/favorite-color.component.ts_0_271 | import {Component} from '@angular/core';
@Component({
selector: 'app-template-favorite-color',
template: `
Favorite Color: <input type="text" [(ngModel)]="favoriteColor">
`,
standalone: false,
})
export class FavoriteColorComponent {
favoriteColor = '';
}
| {
"end_byte": 271,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/template/favorite-color/favorite-color.component.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/template/favorite-color/favorite-color.component.spec.ts_0_1553 | import {ComponentFixture, fakeAsync, TestBed, tick, waitForAsync} from '@angular/core/testing';
import {FormsModule} from '@angular/forms';
import {createNewEvent} from '../../shared/utils';
import {FavoriteColorComponent} from './favorite-color.component';
describe('FavoriteColorComponent', () => {
let component: FavoriteColorComponent;
let fixture: ComponentFixture<FavoriteColorComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [FavoriteColorComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FavoriteColorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
// #docregion model-to-view
it('should update the favorite color on the input field', fakeAsync(() => {
component.favoriteColor = 'Blue';
fixture.detectChanges();
tick();
const input = fixture.nativeElement.querySelector('input');
expect(input.value).toBe('Blue');
}));
// #enddocregion model-to-view
// #docregion view-to-model
it('should update the favorite color in the component', fakeAsync(() => {
const input = fixture.nativeElement.querySelector('input');
const event = createNewEvent('input');
input.value = 'Red';
input.dispatchEvent(event);
fixture.detectChanges();
expect(component.favoriteColor).toEqual('Red');
}));
// #enddocregion view-to-model
});
| {
"end_byte": 1553,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/template/favorite-color/favorite-color.component.spec.ts"
} |
angular/adev/src/content/examples/forms-overview/src/app/shared/utils.ts_0_217 | export function createNewEvent(eventName: string, bubbles = false, cancelable = false) {
const evt = document.createEvent('CustomEvent');
evt.initCustomEvent(eventName, bubbles, cancelable, null);
return evt;
}
| {
"end_byte": 217,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/forms-overview/src/app/shared/utils.ts"
} |
angular/adev/src/content/examples/pipes/BUILD.bazel_0_381 | package(default_visibility = ["//visibility:public"])
exports_files([
"src/app/exponential-strength.pipe.ts",
"src/app/flying-heroes.component.html",
"src/app/flying-heroes.component.ts",
"src/app/flying-heroes.pipe.ts",
"src/app/flying-heroes-impure.component.html",
"src/app/hero-async-message.component.ts",
"src/app/power-booster.component.ts",
])
| {
"end_byte": 381,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/BUILD.bazel"
} |
angular/adev/src/content/examples/pipes/e2e/src/app.e2e-spec.ts_0_4724 | import {browser, element, by} from 'protractor';
describe('Pipes', () => {
beforeAll(() => browser.get(''));
it('should open correctly', async () => {
expect(await element.all(by.tagName('h1')).get(0).getText()).toEqual('Pipes');
expect(await element(by.css('app-birthday p')).getText()).toEqual(
`The hero's birthday is Apr 15, 1988`,
);
});
it('should show 4 heroes', async () => {
expect(await element.all(by.css('app-hero-list div')).count()).toEqual(4);
});
it('should show a familiar hero in json', async () => {
expect(
await element(by.cssContainingText('app-hero-list p', 'Heroes as JSON')).getText(),
).toContain('Bombasto');
});
it('should show alternate birthday formats', async () => {
expect(
await element(
by.cssContainingText('app-birthday-formatting > p', `The hero's birthday is 4/15/88`),
).isDisplayed(),
).toBe(true);
expect(
await element(
by.cssContainingText('app-birthday-formatting > p', `The hero's birthday is Apr 15, 1988`),
).isDisplayed(),
).toBe(true);
});
it('should be able to chain and compose pipes', async () => {
const chainedPipeEles = element.all(
by.cssContainingText('app-birthday-pipe-chaining p', `The chained hero's`),
);
expect(await chainedPipeEles.count()).toBe(2, 'should have 2 chained pipe examples');
expect(await chainedPipeEles.get(0).getText()).toContain('APR 15, 1988');
expect(await chainedPipeEles.get(1).getText()).toContain('FRIDAY, APRIL 15, 1988');
});
it('should be able to use ExponentialStrengthPipe pipe', async () => {
const ele = element(by.css('app-power-booster p'));
expect(await ele.getText()).toContain('Super power boost: 1024');
});
it('should be able to use the exponential calculator', async () => {
const eles = element.all(by.css('app-power-boost-calculator input'));
const baseInputEle = eles.get(0);
const factorInputEle = eles.get(1);
const outputEle = element(by.css('app-power-boost-calculator p'));
await baseInputEle.clear();
await baseInputEle.sendKeys('7');
await factorInputEle.clear();
await factorInputEle.sendKeys('3');
expect(await outputEle.getText()).toContain('343');
});
it('should support flying heroes (pure) ', async () => {
const nameEle = element(by.css('app-flying-heroes input[type="text"]'));
const canFlyCheckEle = element(by.css('app-flying-heroes #can-fly'));
const mutateCheckEle = element(by.css('app-flying-heroes #mutate'));
const resetEle = element(by.css('app-flying-heroes button'));
const flyingHeroesEle = element.all(by.css('app-flying-heroes #flyers div'));
expect(await canFlyCheckEle.getAttribute('checked')).toEqual(
'true',
'should default to "can fly"',
);
expect(await mutateCheckEle.getAttribute('checked')).toEqual(
'true',
'should default to mutating array',
);
expect(await flyingHeroesEle.count()).toEqual(2, 'only two of the original heroes can fly');
await nameEle.sendKeys('test1\n');
expect(await flyingHeroesEle.count()).toEqual(2, 'no change while mutating array');
await mutateCheckEle.click();
await nameEle.sendKeys('test2\n');
expect(await flyingHeroesEle.count()).toEqual(4, 'not mutating; should see both adds');
expect(await flyingHeroesEle.get(2).getText()).toContain('test1');
expect(await flyingHeroesEle.get(3).getText()).toContain('test2');
await resetEle.click();
expect(await flyingHeroesEle.count()).toEqual(2, 'reset should restore original flying heroes');
});
it('should support flying heroes (impure) ', async () => {
const nameEle = element(by.css('app-flying-heroes-impure input[type="text"]'));
const canFlyCheckEle = element(by.css('app-flying-heroes-impure #can-fly'));
const mutateCheckEle = element(by.css('app-flying-heroes-impure #mutate'));
const flyingHeroesEle = element.all(by.css('app-flying-heroes-impure #flyers div'));
expect(await canFlyCheckEle.getAttribute('checked')).toEqual(
'true',
'should default to "can fly"',
);
expect(await mutateCheckEle.getAttribute('checked')).toEqual(
'true',
'should default to mutating array',
);
expect(await flyingHeroesEle.count()).toEqual(2, 'only two of the original heroes can fly');
await nameEle.sendKeys('test1\n');
expect(await flyingHeroesEle.count()).toEqual(
3,
'new flying hero should show in mutating array',
);
});
it('should show an async hero message', async () => {
expect(await element.all(by.tagName('app-hero-async-message')).get(0).getText()).toContain(
'hero',
);
});
});
| {
"end_byte": 4724,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/pipes/src/index.html_0_252 | <!DOCTYPE html>
<html lang="en">
<head>
<title>Pipes</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": 252,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/index.html"
} |
angular/adev/src/content/examples/pipes/src/main.ts_0_426 | import {bootstrapApplication, provideProtractorTestingSupport} from '@angular/platform-browser';
import {provideHttpClient} from '@angular/common/http';
import {AppComponent} from './app/app.component';
bootstrapApplication(AppComponent, {
// HttpClientModule is only used in deprecated HeroListComponent
providers: [
provideHttpClient(),
provideProtractorTestingSupport(), // essential for e2e testing
],
});
| {
"end_byte": 426,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/main.ts"
} |
angular/adev/src/content/examples/pipes/src/app/app.component.html_0_1386 | <h1 id="toc">Pipes</h1>
<a href="#date-pipe">Date Pipe</a>
<a href="#date-pipe-formatting">Date Pipe Formatting</a>
<a href="#pipe-chaining">Pipe Chaining</a>
<a href="#power-booster">Power Booster custom pipe</a>
<a href="#hero-async-message">Async Messages and AsyncPipe</a>
<a href="#json-pipe">Json Pipe for Debugging</a>
<a href="#pipe-precedence">Pipes and Precedence</a>
<a href="#flying-heroes">Flying Heroes filter pipe (pure)</a>
<a href="#flying-heroes-impure">Flying Heroes filter pipe (impure)</a>
<hr>
<h2 id="date-pipe">Date Pipe</h2>
<app-birthday></app-birthday>
<hr>
<h2 id="date-pipe-formatting">Date Pipe Formatting</h2>
<app-birthday-formatting></app-birthday-formatting>
<hr>
<h2 id="pipe-chaining">Pipe Chaining</h2>
<app-birthday-pipe-chaining></app-birthday-pipe-chaining>
<hr>
<app-power-booster id="power-booster"></app-power-booster>
<h2 id="pipe-precedence">Pipes and Precedence</h2>
<app-pipe-precedence></app-pipe-precedence>
<hr>
<app-hero-async-message id="hero-async-message"></app-hero-async-message>
<hr>
<h2 id="json-pipe">Json Pipe for Debugging</h2>
<p>Use the JsonPipe to display component properties for debugging.</p>
<code>data | json</code>
<p>
<app-json-pipe></app-json-pipe>
</p>
<hr>
<app-flying-heroes id="flying-heroes"></app-flying-heroes>
<hr>
<app-flying-heroes-impure id="flying-heroes-impure"></app-flying-heroes-impure>
| {
"end_byte": 1386,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/app.component.html"
} |
angular/adev/src/content/examples/pipes/src/app/birthday.component.ts_0_343 | import {Component} from '@angular/core';
import {DatePipe} from '@angular/common';
@Component({
standalone: true,
selector: 'app-birthday',
templateUrl: './birthday.component.html',
imports: [DatePipe],
})
export class BirthdayComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988 -- since month parameter is zero-based
}
| {
"end_byte": 343,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/birthday.component.ts"
} |
angular/adev/src/content/examples/pipes/src/app/flying-heroes-impure.component.html_0_844 | <!-- #docplaster-->
<!-- #docregion -->
<h2>{{ title }}</h2>
<label for="hero-name">New hero: </label>
<input type="text" id="hero-name" #box (keyup.enter)="addHero(box.value); box.value=''" placeholder="hero name">
<div>
<input id="can-fly" type="checkbox" [(ngModel)]="canFly">
<label for="can-fly">can fly</label>
</div>
<div>
<input id="mutate" type="checkbox" [(ngModel)]="mutate">Mutate array
<button type="button" (click)="reset()">Reset</button>
</div>
<h3>Heroes who fly (piped)</h3>
<div id="flyers">
<!-- #docregion template-flying-heroes -->
@for (hero of (heroes | flyingHeroesImpure); track hero) {
<div>{{ hero.name }}</div>
}
<!-- #enddocregion template-flying-heroes -->
</div>
<h3>All Heroes (no pipe)</h3>
<div id="all">
@for (hero of heroes; track hero) {
<div>{{ hero.name }}</div>
}
</div>
| {
"end_byte": 844,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/flying-heroes-impure.component.html"
} |
angular/adev/src/content/examples/pipes/src/app/json-pipe.component.ts_0_365 | import {Component} from '@angular/core';
import {JsonPipe} from '@angular/common';
@Component({
standalone: true,
selector: 'app-json-pipe',
template: `{{ data | json }}`,
imports: [JsonPipe],
})
export class JsonPipeComponent {
data = {
name: 'John Doe',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
},
};
}
| {
"end_byte": 365,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/json-pipe.component.ts"
} |
angular/adev/src/content/examples/pipes/src/app/birthday-pipe-chaining.component.html_0_209 | <p>
The chained hero's uppercase birthday is
{{ birthday | date | uppercase }}
</p>
<p>
The chained hero's uppercase birthday in "fullDate" format is
{{ birthday | date:'fullDate' | uppercase }}
</p>
| {
"end_byte": 209,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/birthday-pipe-chaining.component.html"
} |
angular/adev/src/content/examples/pipes/src/app/power-booster.component.ts_0_364 | import {Component} from '@angular/core';
import {ExponentialStrengthPipe} from './exponential-strength.pipe';
@Component({
standalone: true,
selector: 'app-power-booster',
template: `
<h2>Power Booster</h2>
<p>Super power boost: {{2 | exponentialStrength: 10}}</p>
`,
imports: [ExponentialStrengthPipe],
})
export class PowerBoosterComponent {}
| {
"end_byte": 364,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/power-booster.component.ts"
} |
angular/adev/src/content/examples/pipes/src/app/flying-heroes.pipe.ts_0_685 | // #docregion
// #docregion pure
import {Pipe, PipeTransform} from '@angular/core';
import {Hero} from './heroes';
@Pipe({
standalone: true,
name: 'flyingHeroes',
})
export class FlyingHeroesPipe implements PipeTransform {
transform(allHeroes: Hero[]) {
// #docregion filter
return allHeroes.filter((hero) => hero.canFly);
// #enddocregion filter
}
}
// #enddocregion pure
/////// Identical except for the pure flag
// #docregion impure
// #docregion pipe-decorator
@Pipe({
standalone: true,
name: 'flyingHeroesImpure',
pure: false,
})
// #enddocregion pipe-decorator
export class FlyingHeroesImpurePipe extends FlyingHeroesPipe {}
// #enddocregion impure
| {
"end_byte": 685,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/flying-heroes.pipe.ts"
} |
angular/adev/src/content/examples/pipes/src/app/heroes.ts_0_241 | export interface Hero {
name: string;
canFly: boolean;
}
export const HEROES: Hero[] = [
{name: 'Windstorm', canFly: true},
{name: 'Bombasto', canFly: false},
{name: 'Magneto', canFly: false},
{name: 'Tornado', canFly: true},
];
| {
"end_byte": 241,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/heroes.ts"
} |
angular/adev/src/content/examples/pipes/src/app/birthday.component.html_0_52 | <p>The hero's birthday is {{ birthday | date }}</p>
| {
"end_byte": 52,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/birthday.component.html"
} |
angular/adev/src/content/examples/pipes/src/app/app.component.ts_0_1339 | import {Component} from '@angular/core';
import {BirthdayComponent} from './birthday.component';
import {BirthdayFormattingComponent} from './birthday-formatting.component';
import {BirthdayPipeChainingComponent} from './birthday-pipe-chaining.component';
import {FlyingHeroesComponent, FlyingHeroesImpureComponent} from './flying-heroes.component';
import {HeroAsyncMessageComponent} from './hero-async-message.component';
import {PrecedenceComponent} from './precedence.component';
import {JsonPipeComponent} from './json-pipe.component';
import {PowerBoosterComponent} from './power-booster.component';
@Component({
standalone: true,
selector: 'app-root',
templateUrl: './app.component.html',
imports: [
// Example components
BirthdayComponent,
BirthdayFormattingComponent,
BirthdayPipeChainingComponent,
FlyingHeroesComponent,
FlyingHeroesImpureComponent,
HeroAsyncMessageComponent,
PrecedenceComponent,
JsonPipeComponent,
PowerBoosterComponent,
],
styles: [
'a[href] {display: block; padding: 10px 0;}',
'a:hover {text-decoration: none;}',
'h2 {margin: 0;}',
'code {font-family: monospace; background-color: #eee; padding: 0.5em;}',
],
})
export class AppComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988 -- since month parameter is zero-based
}
| {
"end_byte": 1339,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/app.component.ts"
} |
angular/adev/src/content/examples/pipes/src/app/hero-async-message.component.ts_0_964 | import {Component} from '@angular/core';
import {AsyncPipe} from '@angular/common';
import {Observable, interval} from 'rxjs';
import {map, startWith, take} from 'rxjs/operators';
@Component({
standalone: true,
selector: 'app-hero-async-message',
template: `
<h2>Async Messages and AsyncPipe</h2>
<p>{{ message$ | async }}</p>
<button type="button" (click)="resend()">Resend Messages</button>`,
imports: [AsyncPipe],
})
export class HeroAsyncMessageComponent {
message$: Observable<string>;
private messages = ['You are my hero!', 'You are the best hero!', 'Will you be my hero?'];
constructor() {
this.message$ = this.getResendObservable();
}
resend() {
this.message$ = this.getResendObservable();
}
private getResendObservable() {
return interval(1000).pipe(
map((i) => `Message #${i + 1}: ${this.messages[i]}`),
take(this.messages.length),
startWith('Waiting for messages...'),
);
}
}
| {
"end_byte": 964,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/hero-async-message.component.ts"
} |
angular/adev/src/content/examples/pipes/src/app/precedence.component.html_0_1138 | <!-- #docregion -->
<!-- #docregion precedence -->
<p>
In most cases, you'll wrap the entire ternary expression in parentheses before passing the result to a pipe.
</p>
<p>
Example: <code>(isLeft ? 'left' : 'right') | uppercase</code>
<b>
{{ (isLeft ? 'left' : 'right') | uppercase }}
</b>
</p>
<button type="button" (click)="toggleDirection()">Toggle 'isLeft'</button>
<p>Without parentheses, only the second value is uppercased.</p>
<p>Example: <code>isGood ? 'good' : 'bad' | uppercase</code>
<b>
{{ isGood ? 'good' : 'bad' | uppercase }}
</b>
</p>
<p>Same as: <code>isGood ? 'good' : ('bad' | uppercase)</code>
<b>
{{ isGood ? 'good' : ('bad' | uppercase) }}
</b>
</p>
<button type="button" (click)="toggleGood()">Toggle 'isGood'</button>
<p>If only one of the values should be passed to a pipe,
be explicit and surround that value with parentheses.</p>
<p>Example: <code>isUpper ? ('upper' | uppercase) : 'lower'</code>
<b>
{{ isUpper ? ('upper' | uppercase) : 'lower' }}
</b>
</p>
<button type="button" (click)="toggleCase()">Toggle 'isUpper'</button>
<!-- #enddocregion precedence -->
| {
"end_byte": 1138,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/precedence.component.html"
} |
angular/adev/src/content/examples/pipes/src/app/flying-heroes.component.ts_0_1985 | // #docplaster
// #docregion
import {Component} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {FlyingHeroesPipe, FlyingHeroesImpurePipe} from './flying-heroes.pipe';
import {HEROES} from './heroes';
@Component({
standalone: true,
selector: 'app-flying-heroes',
templateUrl: './flying-heroes.component.html',
imports: [CommonModule, FormsModule, FlyingHeroesPipe],
styles: [
`
#flyers, #all {font-style: italic}
button {display: block}
input {margin: .25rem .25rem .5rem 0;}
`,
],
})
// #docregion v1
export class FlyingHeroesComponent {
heroes: any[] = [];
canFly = true;
// #enddocregion v1
mutate = true;
title = 'Flying Heroes (pure pipe)';
// #docregion v1
constructor() {
this.reset();
}
addHero(name: string) {
name = name.trim();
if (!name) {
return;
}
const hero = {name, canFly: this.canFly};
// #enddocregion v1
if (this.mutate) {
// Pure pipe won't update display because heroes array reference is unchanged
// Impure pipe will display
// #docregion v1
// #docregion push
this.heroes.push(hero);
// #enddocregion push
// #enddocregion v1
} else {
// Pipe updates display because heroes array is a new object
this.heroes = this.heroes.concat(hero);
}
// #docregion v1
}
reset() {
this.heroes = HEROES.slice();
}
}
// #enddocregion v1
////// Identical except for impure pipe //////
@Component({
standalone: true,
selector: 'app-flying-heroes-impure',
templateUrl: './flying-heroes-impure.component.html',
imports: [CommonModule, FormsModule, FlyingHeroesImpurePipe],
styles: [
'#flyers, #all {font-style: italic}',
'button {display: block}',
'input {margin: .25rem .25rem .5rem 0;}',
],
})
export class FlyingHeroesImpureComponent extends FlyingHeroesComponent {
override title = 'Flying Heroes (impure pipe)';
}
| {
"end_byte": 1985,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/flying-heroes.component.ts"
} |
angular/adev/src/content/examples/pipes/src/app/flying-heroes.component.html_0_1162 | <!-- #docplaster-->
<!-- #docregion -->
<h2>{{ title }}</h2>
<p>Create a new hero and press enter to add it to the list. </p>
<!-- #docregion template-1 -->
<label for="hero-name">New hero name: </label>
<input type="text" #box id="hero-name" (keyup.enter)="addHero(box.value); box.value=''" placeholder="hero name">
<!-- #enddocregion template-1 -->
<div>
<input id="can-fly" type="checkbox" [(ngModel)]="canFly">
<label for="can-fly">Hero can fly</label>
</div>
<div>
<input id="mutate" type="checkbox" [(ngModel)]="mutate">
<label for="mutate">Mutate array</label>
<!-- #docregion template-1 -->
<button type="button" (click)="reset()">Reset list of heroes</button>
<!-- #enddocregion template-1 -->
</div>
<h3>Heroes who fly (piped)</h3>
<div id="flyers">
<!-- #docregion template-flying-heroes -->
@for (hero of (heroes | flyingHeroes); track hero) {
<div>{{ hero.name }}</div>
}
<!-- #enddocregion template-flying-heroes -->
</div>
<h3>All Heroes (no pipe)</h3>
<div id="all">
<!-- #docregion template-1 -->
@for (hero of heroes; track hero) {
<div>{{ hero.name }}</div>
}
<!-- #enddocregion template-1 -->
</div>
| {
"end_byte": 1162,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/flying-heroes.component.html"
} |
angular/adev/src/content/examples/pipes/src/app/birthday-formatting.component.ts_0_522 | import {Component} from '@angular/core';
import {DatePipe} from '@angular/common';
@Component({
standalone: true,
selector: 'app-birthday-formatting',
templateUrl: './birthday-formatting.component.html',
imports: [DatePipe],
})
export class BirthdayFormattingComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988 -- since month parameter is zero-based
toggle = true;
get format() {
return this.toggle ? 'mediumDate' : 'fullDate';
}
toggleFormat() {
this.toggle = !this.toggle;
}
}
| {
"end_byte": 522,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/birthday-formatting.component.ts"
} |
angular/adev/src/content/examples/pipes/src/app/precedence.component.ts_0_577 | import {Component} from '@angular/core';
import {UpperCasePipe} from '@angular/common';
@Component({
standalone: true,
selector: 'app-pipe-precedence',
templateUrl: './precedence.component.html',
imports: [UpperCasePipe],
styles: ['code {font-family: monospace; background-color: #eee; padding: 0.5em;}'],
})
export class PrecedenceComponent {
isLeft = true;
toggleDirection() {
this.isLeft = !this.isLeft;
}
isGood = true;
toggleGood() {
this.isGood = !this.isGood;
}
isUpper = true;
toggleCase() {
this.isUpper = !this.isUpper;
}
}
| {
"end_byte": 577,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/precedence.component.ts"
} |
angular/adev/src/content/examples/pipes/src/app/exponential-strength.pipe.ts_0_539 | import {Pipe, PipeTransform} from '@angular/core';
/*
* Raise the value exponentially
* Takes an exponent argument that defaults to 1.
* Usage:
* value | exponentialStrength:exponent
* Example:
* {{ 2 | exponentialStrength:10 }}
* formats to: 1024
*/
// #docregion pipe-class
@Pipe({
standalone: true,
name: 'exponentialStrength',
})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent = 1): number {
return Math.pow(value, exponent);
}
}
// #enddocregion pipe-class
| {
"end_byte": 539,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/exponential-strength.pipe.ts"
} |
angular/adev/src/content/examples/pipes/src/app/birthday-formatting.component.html_0_293 | <p>The hero's birthday is {{ birthday | date:"shortDate" }} in the "shortDate" format.</p>
<p>The hero's birthday is {{ birthday | date:format }} in "{{ format }}" format.
Click the toggle button to change formats.</p>
<button type="button" (click)="toggleFormat()">Toggle Format</button>
| {
"end_byte": 293,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/birthday-formatting.component.html"
} |
angular/adev/src/content/examples/pipes/src/app/birthday-pipe-chaining.component.ts_0_413 | import {Component} from '@angular/core';
import {DatePipe, UpperCasePipe} from '@angular/common';
@Component({
standalone: true,
selector: 'app-birthday-pipe-chaining',
templateUrl: './birthday-pipe-chaining.component.html',
imports: [DatePipe, UpperCasePipe],
})
export class BirthdayPipeChainingComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988 -- since month parameter is zero-based
}
| {
"end_byte": 413,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/pipes/src/app/birthday-pipe-chaining.component.ts"
} |
angular/adev/src/content/examples/testing/BUILD.bazel_0_1800 | package(default_visibility = ["//visibility:public"])
exports_files([
"src/app/about/about.component.spec.ts",
"src/app/about/about.component.ts",
"src/app/app.component.html",
"src/app/app.component.spec.ts",
"src/app/banner/banner.component.detect-changes.spec.ts",
"src/app/banner/banner.component.spec.ts",
"src/app/banner/banner.component.ts",
"src/app/banner/banner-external.component.spec.ts",
"src/app/banner/banner-external.component.ts",
"src/app/banner/banner-initial.component.spec.ts",
"src/app/dashboard/dashboard.component.html",
"src/app/dashboard/dashboard.component.spec.ts",
"src/app/dashboard/dashboard.component.ts",
"src/app/dashboard/dashboard-hero.component.spec.ts",
"src/app/dashboard/dashboard-hero.component.ts",
"src/app/demo/async-helper.spec.ts",
"src/app/demo/demo.spec.ts",
"src/app/demo/demo.testbed.spec.ts",
"src/app/demo/demo.ts",
"src/app/hero/hero-detail.component.html",
"src/app/hero/hero-detail.component.spec.ts",
"src/app/hero/hero-detail.component.ts",
"src/app/hero/hero-detail.service.ts",
"src/app/hero/hero-list.component.spec.ts",
"src/app/model/hero.service.spec.ts",
"src/app/shared/canvas.component.spec.ts",
"src/app/shared/canvas.component.ts",
"src/app/shared/highlight.directive.spec.ts",
"src/app/shared/highlight.directive.ts",
"src/app/shared/title-case.pipe.spec.ts",
"src/app/shared/title-case.pipe.ts",
"src/app/twain/twain.component.marbles.spec.ts",
"src/app/twain/twain.component.spec.ts",
"src/app/twain/twain.component.ts",
"src/app/welcome/welcome.component.spec.ts",
"src/app/welcome/welcome.component.ts",
"src/testing/async-observable-helpers.ts",
"src/testing/index.ts",
])
| {
"end_byte": 1800,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/BUILD.bazel"
} |
angular/adev/src/content/examples/testing/e2e/src/app.e2e-spec.ts_0_807 | import {browser, element, by} from 'protractor';
describe('Testing Example', () => {
const expectedViewNames = ['Dashboard', 'Heroes', 'About'];
beforeAll(() => browser.get(''));
function getPageElts() {
return {
navElts: element.all(by.css('app-root nav a')),
appDashboard: element(by.css('app-root app-dashboard')),
};
}
it('has title', async () => {
expect(await browser.getTitle()).toEqual('App Under Test');
});
it(`has views ${expectedViewNames}`, async () => {
const viewNames = await getPageElts().navElts.map((el) => el!.getText());
expect(viewNames).toEqual(expectedViewNames);
});
it('has dashboard as the active view', async () => {
const page = getPageElts();
expect(await page.appDashboard.isPresent()).toBeTruthy();
});
});
| {
"end_byte": 807,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/e2e/src/app.e2e-spec.ts"
} |
angular/adev/src/content/examples/testing/src/index.html_0_291 | <!-- Run the test app-->
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/" />
<title>App Under Test</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<app-root></app-root>
</body>
</html>
| {
"end_byte": 291,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/index.html"
} |
angular/adev/src/content/examples/testing/src/main.ts_0_265 | // main app entry point
import {bootstrapApplication} from '@angular/platform-browser';
import {AppComponent} from './app/app.component';
import {appConfig} from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));
| {
"end_byte": 265,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/main.ts"
} |
angular/adev/src/content/examples/testing/src/index-specs.html_0_147 | <!--
Intentionally empty placeholder for Stackblitz.
Do not need index.html in zip-download either as you should run tests with `npm test`
-->
| {
"end_byte": 147,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/index-specs.html"
} |
angular/adev/src/content/examples/testing/src/expected.ts_0_89 | /* Ignore. Satisfies static analysis of router config in app.component.router.spec.ts */
| {
"end_byte": 89,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/expected.ts"
} |
angular/adev/src/content/examples/testing/src/test.css_0_54 | @import '~jasmine-core/lib/jasmine-core/jasmine.css';
| {
"end_byte": 54,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/test.css"
} |
angular/adev/src/content/examples/testing/src/app/app.component.html_0_289 | <!-- #docregion -->
<app-banner></app-banner>
<app-welcome></app-welcome>
<!-- #docregion links -->
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
<a routerLink="/about">About</a>
</nav>
<!-- #enddocregion links -->
<router-outlet></router-outlet>
| {
"end_byte": 289,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/app.component.html"
} |
angular/adev/src/content/examples/testing/src/app/in-memory-data.service.ts_0_701 | import {InMemoryDbService} from 'angular-in-memory-web-api';
import {QUOTES} from './twain/twain.data';
// Adjust to reduce number of quotes
const maxQuotes = Infinity; // 0;
/** Create in-memory database of heroes and quotes */
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const heroes = [
{id: 12, name: 'Dr. Nice'},
{id: 13, name: 'Bombasto'},
{id: 14, name: 'Celeritas'},
{id: 15, name: 'Magneta'},
{id: 16, name: 'RubberMan'},
{id: 17, name: 'Dynama'},
{id: 18, name: 'Dr. IQ'},
{id: 19, name: 'Magma'},
{id: 20, name: 'Tornado'},
];
return {heroes, quotes: QUOTES.slice(0, maxQuotes)};
}
}
| {
"end_byte": 701,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/in-memory-data.service.ts"
} |
angular/adev/src/content/examples/testing/src/app/app-initial.component.ts_0_273 | // #docregion
// Reduced version of the initial AppComponent generated by CLI
import {Component} from '@angular/core';
@Component({
standalone: true,
selector: 'app-root',
template: '<h1>Welcome to {{title}}!</h1>',
})
export class AppComponent {
title = 'app';
}
| {
"end_byte": 273,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/app-initial.component.ts"
} |
angular/adev/src/content/examples/testing/src/app/app.routes.ts_0_429 | import {Routes} from '@angular/router';
import {AboutComponent} from './about/about.component';
import {DashboardComponent} from './dashboard/dashboard.component';
export const routes: Routes = [
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{path: 'about', component: AboutComponent},
{path: 'dashboard', component: DashboardComponent},
{path: 'heroes', loadChildren: () => import('./hero/hero.routes')},
];
| {
"end_byte": 429,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/app.routes.ts"
} |
angular/adev/src/content/examples/testing/src/app/app.component.spec.ts_0_3598 | // #docplaster
import {Component, DebugElement, NO_ERRORS_SCHEMA} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed, tick, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {provideRouter, Router, RouterLink} from '@angular/router';
import {AppComponent} from './app.component';
import {appConfig} from './app.config';
import {UserService} from './model';
// #docregion component-stubs
@Component({standalone: true, selector: 'app-banner', template: ''})
class BannerStubComponent {}
@Component({standalone: true, selector: 'router-outlet', template: ''})
class RouterOutletStubComponent {}
@Component({standalone: true, selector: 'app-welcome', template: ''})
class WelcomeStubComponent {}
// #enddocregion component-stubs
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
describe('AppComponent & TestModule', () => {
beforeEach(waitForAsync(() => {
// #docregion testbed-stubs
TestBed.configureTestingModule(
Object.assign({}, appConfig, {
imports: [
AppComponent,
BannerStubComponent,
RouterLink,
RouterOutletStubComponent,
WelcomeStubComponent,
],
providers: [provideRouter([]), UserService],
}),
)
// #enddocregion testbed-stubs
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
});
}));
tests();
});
//////// Testing w/ NO_ERRORS_SCHEMA //////
describe('AppComponent & NO_ERRORS_SCHEMA', () => {
beforeEach(waitForAsync(() => {
// #docregion no-errors-schema, mixed-setup
TestBed.configureTestingModule(
Object.assign({}, appConfig, {
imports: [
AppComponent,
// #enddocregion no-errors-schema
BannerStubComponent,
// #docregion no-errors-schema
RouterLink,
],
providers: [provideRouter([]), UserService],
schemas: [NO_ERRORS_SCHEMA],
}),
)
// #enddocregion no-errors-schema, mixed-setup
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
});
}));
tests();
});
function tests() {
let routerLinks: RouterLink[];
let linkDes: DebugElement[];
// #docregion test-setup
beforeEach(() => {
fixture.detectChanges(); // trigger initial data binding
// find DebugElements with an attached RouterLinkStubDirective
linkDes = fixture.debugElement.queryAll(By.directive(RouterLink));
// get attached link directive instances
// using each DebugElement's injector
routerLinks = linkDes.map((de) => de.injector.get(RouterLink));
});
// #enddocregion test-setup
it('can instantiate the component', () => {
expect(comp).not.toBeNull();
});
// #docregion tests
it('can get RouterLinks from template', () => {
expect(routerLinks.length).withContext('should have 3 routerLinks').toBe(3);
expect(routerLinks[0].href).toBe('/dashboard');
expect(routerLinks[1].href).toBe('/heroes');
expect(routerLinks[2].href).toBe('/about');
});
it('can click Heroes link in template', fakeAsync(() => {
const heroesLinkDe = linkDes[1]; // heroes link DebugElement
TestBed.inject(Router).resetConfig([{path: '**', children: []}]);
heroesLinkDe.triggerEventHandler('click', {button: 0});
tick();
fixture.detectChanges();
expect(TestBed.inject(Router).url).toBe('/heroes');
}));
// #enddocregion tests
}
| {
"end_byte": 3598,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/app.component.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/app.component.router.spec.ts_0_5292 | // For more examples:
// https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts
import {Location} from '@angular/common';
import {provideLocationMocks, SpyLocation} from '@angular/common/testing';
import {DebugElement, Type} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed, tick, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {provideRouter, Router, RouterLink} from '@angular/router';
import {asyncData, click} from '../testing';
import {AboutComponent} from './about/about.component';
import {AppComponent} from './app.component';
import {DashboardComponent} from './dashboard/dashboard.component';
import {HeroService, TestHeroService} from './model/testing/test-hero.service';
import {TwainService} from './twain/twain.service';
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let page: Page;
let router: Router;
let location: SpyLocation;
describe('AppComponent & router testing', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule(
Object.assign({}, appConfig, {
providers: [
{provide: HeroService, useClass: TestHeroService},
UserService,
TwainService,
provideHttpClient(),
provideLocationMocks(),
provideRouter([
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{path: 'about', component: AboutComponent},
{path: 'dashboard', component: DashboardComponent},
]),
],
}),
).compileComponents();
}));
it('should navigate to "Dashboard" immediately', fakeAsync(() => {
createComponent();
tick(); // wait for async data to arrive
expectPathToBe('/dashboard', 'after initialNavigation()');
expectElementOf(DashboardComponent);
}));
it('should navigate to "About" on click', fakeAsync(() => {
createComponent();
click(page.aboutLinkDe);
// page.aboutLinkDe.nativeElement.click(); // ok but fails in phantom
advance();
expectPathToBe('/about');
expectElementOf(AboutComponent);
}));
it('should navigate to "About" w/ browser location URL change', fakeAsync(() => {
createComponent();
location.simulateHashChange('/about');
advance();
expectPathToBe('/about');
expectElementOf(AboutComponent);
}));
// Can't navigate to lazy loaded modules with this technique
xit('should navigate to "Heroes" on click (not working yet)', fakeAsync(() => {
createComponent();
page.heroesLinkDe.nativeElement.click();
advance();
expectPathToBe('/heroes');
}));
});
///////////////
import {HeroListComponent} from './hero/hero-list.component';
import {appConfig} from './app.config';
import heroRoutes from './hero/hero.routes';
import {UserService} from './model';
import {provideHttpClient} from '@angular/common/http';
///////// Can't get lazy loaded Heroes to work yet
xdescribe('AppComponent & Lazy Loading (not working yet)', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule(appConfig).compileComponents();
}));
beforeEach(fakeAsync(() => {
createComponent();
router.resetConfig([{path: 'heroes', loadChildren: () => heroRoutes}]);
}));
it('should navigate to "Heroes" on click', waitForAsync(() => {
page.heroesLinkDe.nativeElement.click();
advance();
expectPathToBe('/heroes');
expectElementOf(HeroListComponent);
}));
it('can navigate to "Heroes" w/ browser location URL change', fakeAsync(() => {
location.go('/heroes');
advance();
expectPathToBe('/heroes');
expectElementOf(HeroListComponent);
}));
});
////// Helpers /////////
/**
* Advance to the routed page
* Wait a tick, then detect changes, and tick again
*/
function advance(): void {
tick(); // wait while navigating
fixture.detectChanges(); // update view
tick(); // wait for async data to arrive
}
function createComponent() {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
const injector = fixture.debugElement.injector;
location = injector.get(Location) as SpyLocation;
router = injector.get(Router);
router.initialNavigation();
spyOn(injector.get(TwainService), 'getQuote')
// fake fast async observable
.and.returnValue(asyncData('Test Quote'));
advance();
page = new Page();
}
class Page {
aboutLinkDe: DebugElement;
dashboardLinkDe: DebugElement;
heroesLinkDe: DebugElement;
// for debugging
comp: AppComponent;
router: Router;
fixture: ComponentFixture<AppComponent>;
constructor() {
const links = fixture.debugElement.queryAll(By.directive(RouterLink));
this.aboutLinkDe = links[2];
this.dashboardLinkDe = links[0];
this.heroesLinkDe = links[1];
// for debugging
this.comp = comp;
this.fixture = fixture;
this.router = router;
}
}
function expectPathToBe(path: string, expectationFailOutput?: any) {
expect(location.path())
.withContext(expectationFailOutput || 'location.path()')
.toEqual(path);
}
function expectElementOf(type: Type<any>): any {
const el = fixture.debugElement.query(By.directive(type));
expect(el).withContext(`expected an element for ${type.name}`).toBeTruthy();
return el;
}
| {
"end_byte": 5292,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/app.component.router.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/app.component.ts_0_438 | // #docregion
import {Component} from '@angular/core';
import {RouterLink, RouterOutlet} from '@angular/router';
import {BannerComponent} from './banner/banner.component';
import {WelcomeComponent} from './welcome/welcome.component';
@Component({
standalone: true,
selector: 'app-root',
templateUrl: './app.component.html',
imports: [BannerComponent, WelcomeComponent, RouterOutlet, RouterLink],
})
export class AppComponent {}
| {
"end_byte": 438,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/app.component.ts"
} |
angular/adev/src/content/examples/testing/src/app/app.config.ts_0_1124 | import {provideHttpClient} from '@angular/common/http';
import {ApplicationConfig, importProvidersFrom} from '@angular/core';
import {provideProtractorTestingSupport} from '@angular/platform-browser';
import {provideRouter} from '@angular/router';
import {HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api';
import {routes} from './app.routes';
import {InMemoryDataService} from './in-memory-data.service';
import {HeroService} from './model/hero.service';
import {UserService} from './model/user.service';
import {TwainService} from './twain/twain.service';
export const appProviders = [
provideRouter(routes),
provideHttpClient(),
provideProtractorTestingSupport(),
importProvidersFrom(
// The HttpClientInMemoryWebApiModule module intercepts HTTP requests
// and returns simulated server responses.
// Remove it when a real server is ready to receive requests.
HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, {dataEncapsulation: false}),
),
HeroService,
TwainService,
UserService,
];
export const appConfig: ApplicationConfig = {
providers: appProviders,
};
| {
"end_byte": 1124,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/app.config.ts"
} |
angular/adev/src/content/examples/testing/src/app/app-initial.component.spec.ts_0_2050 | // #docplaster
// #docregion
import {TestBed, waitForAsync} from '@angular/core/testing';
// #enddocregion
import {AppComponent} from './app-initial.component';
/*
// #docregion
import { AppComponent } from './app.component';
describe('AppComponent', () => {
// #enddocregion
*/
describe('AppComponent (initial CLI version)', () => {
// #docregion
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
}));
it('should create the app', waitForAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
}));
it("should have as title 'app'", waitForAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title', waitForAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Welcome to app!');
}));
});
// #enddocregion
/// As it should be
import {DebugElement} from '@angular/core';
import {ComponentFixture} from '@angular/core/testing';
describe('AppComponent (initial CLI version - as it should be)', () => {
let app: AppComponent;
let de: DebugElement;
let fixture: ComponentFixture<AppComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppComponent],
});
fixture = TestBed.createComponent(AppComponent);
app = fixture.componentInstance;
de = fixture.debugElement;
});
it('should create the app', () => {
expect(app).toBeDefined();
});
it("should have as title 'app'", () => {
expect(app.title).toEqual('app');
});
it('should render title in an h1 tag', () => {
fixture.detectChanges();
expect(de.nativeElement.querySelector('h1').textContent).toContain('Welcome to app!');
});
});
| {
"end_byte": 2050,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/app-initial.component.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo.spec.ts_0_5074 | // #docplaster
import {LightswitchComponent, MasterService, ValueService, ReversePipe} from './demo';
///////// Fakes /////////
export class FakeValueService extends ValueService {
override value = 'faked service value';
}
////////////////////////
describe('demo (no TestBed):', () => {
// #docregion ValueService
// Straight Jasmine testing without Angular's testing support
describe('ValueService', () => {
let service: ValueService;
beforeEach(() => {
service = new ValueService();
});
it('#getValue should return real value', () => {
expect(service.getValue()).toBe('real value');
});
it('#getObservableValue should return value from observable', (done: DoneFn) => {
service.getObservableValue().subscribe((value) => {
expect(value).toBe('observable value');
done();
});
});
it('#getPromiseValue should return value from a promise', (done: DoneFn) => {
service.getPromiseValue().then((value) => {
expect(value).toBe('promise value');
done();
});
});
});
// #enddocregion ValueService
// MasterService requires injection of a ValueService
// #docregion MasterService
describe('MasterService without Angular testing support', () => {
let masterService: MasterService;
it('#getValue should return real value from the real service', () => {
masterService = new MasterService(new ValueService());
expect(masterService.getValue()).toBe('real value');
});
it('#getValue should return faked value from a fakeService', () => {
masterService = new MasterService(new FakeValueService());
expect(masterService.getValue()).toBe('faked service value');
});
it('#getValue should return faked value from a fake object', () => {
const fake = {getValue: () => 'fake value'};
masterService = new MasterService(fake as ValueService);
expect(masterService.getValue()).toBe('fake value');
});
it('#getValue should return stubbed value from a spy', () => {
// create `getValue` spy on an object representing the ValueService
const valueServiceSpy = jasmine.createSpyObj('ValueService', ['getValue']);
// set the value to return when the `getValue` spy is called.
const stubValue = 'stub value';
valueServiceSpy.getValue.and.returnValue(stubValue);
masterService = new MasterService(valueServiceSpy);
expect(masterService.getValue()).withContext('service returned stub value').toBe(stubValue);
expect(valueServiceSpy.getValue.calls.count())
.withContext('spy method was called once')
.toBe(1);
expect(valueServiceSpy.getValue.calls.mostRecent().returnValue).toBe(stubValue);
});
});
// #enddocregion MasterService
describe('MasterService (no beforeEach)', () => {
// #docregion no-before-each-test
it('#getValue should return stubbed value from a spy', () => {
// #docregion no-before-each-setup-call
const {masterService, stubValue, valueServiceSpy} = setup();
// #enddocregion no-before-each-setup-call
expect(masterService.getValue()).withContext('service returned stub value').toBe(stubValue);
expect(valueServiceSpy.getValue.calls.count())
.withContext('spy method was called once')
.toBe(1);
expect(valueServiceSpy.getValue.calls.mostRecent().returnValue).toBe(stubValue);
});
// #enddocregion no-before-each-test
// #docregion no-before-each-setup
function setup() {
const valueServiceSpy = jasmine.createSpyObj('ValueService', ['getValue']);
const stubValue = 'stub value';
const masterService = new MasterService(valueServiceSpy);
valueServiceSpy.getValue.and.returnValue(stubValue);
return {masterService, stubValue, valueServiceSpy};
}
// #enddocregion no-before-each-setup
});
describe('ReversePipe', () => {
let pipe: ReversePipe;
beforeEach(() => {
pipe = new ReversePipe();
});
it('transforms "abc" to "cba"', () => {
expect(pipe.transform('abc')).toBe('cba');
});
it('no change to palindrome: "able was I ere I saw elba"', () => {
const palindrome = 'able was I ere I saw elba';
expect(pipe.transform(palindrome)).toBe(palindrome);
});
});
// #docregion Lightswitch
describe('LightswitchComp', () => {
it('#clicked() should toggle #isOn', () => {
const comp = new LightswitchComponent();
expect(comp.isOn).withContext('off at first').toBe(false);
comp.clicked();
expect(comp.isOn).withContext('on after click').toBe(true);
comp.clicked();
expect(comp.isOn).withContext('off after second click').toBe(false);
});
it('#clicked() should set #message to "is on"', () => {
const comp = new LightswitchComponent();
expect(comp.message)
.withContext('off at first')
.toMatch(/is off/i);
comp.clicked();
expect(comp.message).withContext('on after clicked').toMatch(/is on/i);
});
});
// #enddocregion Lightswitch
});
| {
"end_byte": 5074,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo.ts_0_7254 | /* eslint-disable @angular-eslint/directive-selector, guard-for-in, @angular-eslint/no-input-rename
*/
import {
Component,
ContentChildren,
Directive,
EventEmitter,
HostBinding,
HostListener,
Injectable,
Input,
OnChanges,
OnDestroy,
OnInit,
Optional,
Output,
Pipe,
PipeTransform,
SimpleChanges,
} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {of} from 'rxjs';
import {delay} from 'rxjs/operators';
import {sharedImports} from '../shared/shared';
////////// The App: Services and Components for the tests. //////////////
export interface Hero {
name: string;
}
////////// Services ///////////////
@Injectable()
export class ValueService {
value = 'real value';
getValue() {
return this.value;
}
setValue(value: string) {
this.value = value;
}
getObservableValue() {
return of('observable value');
}
getPromiseValue() {
return Promise.resolve('promise value');
}
getObservableDelayValue() {
return of('observable delay value').pipe(delay(10));
}
}
// #docregion MasterService
@Injectable()
export class MasterService {
constructor(private valueService: ValueService) {}
getValue() {
return this.valueService.getValue();
}
}
// #enddocregion MasterService
/////////// Pipe ////////////////
/*
* Reverse the input string.
*/
@Pipe({name: 'reverse', standalone: true})
export class ReversePipe implements PipeTransform {
transform(s: string) {
let r = '';
for (let i = s.length; i; ) {
r += s[--i];
}
return r;
}
}
//////////// Components /////////////
@Component({
standalone: true,
selector: 'bank-account',
template: ` Bank Name: {{ bank }} Account Id: {{ id }} `,
})
export class BankAccountComponent {
@Input() bank = '';
@Input('account') id = '';
// Removed on 12/02/2016 when ceased public discussion of the `Renderer`. Revive in future?
// constructor(private renderer: Renderer, private el: ElementRef ) {
// renderer.setElementProperty(el.nativeElement, 'customProperty', true);
// }
}
/** A component with attributes, styles, classes, and property setting */
@Component({
standalone: true,
selector: 'bank-account-parent',
template: `
<bank-account
bank="RBC"
account="4747"
[style.width.px]="width"
[style.color]="color"
[class.closed]="isClosed"
[class.open]="!isClosed"
>
</bank-account>
`,
imports: [BankAccountComponent],
})
export class BankAccountParentComponent {
width = 200;
color = 'red';
isClosed = true;
}
// #docregion LightswitchComp
@Component({
standalone: true,
selector: 'lightswitch-comp',
template: ` <button type="button" (click)="clicked()">Click me!</button>
<span>{{ message }}</span>`,
})
export class LightswitchComponent {
isOn = false;
clicked() {
this.isOn = !this.isOn;
}
get message() {
return `The light is ${this.isOn ? 'On' : 'Off'}`;
}
}
// #enddocregion LightswitchComp
@Component({
standalone: true,
selector: 'child-1',
template: '<span>Child-1({{text}})</span>',
})
export class Child1Component {
@Input() text = 'Original';
}
@Component({
standalone: true,
selector: 'child-2',
template: '<div>Child-2({{text}})</div>',
})
export class Child2Component {
@Input() text = '';
}
@Component({
standalone: true,
selector: 'child-3',
template: '<div>Child-3({{text}})</div>',
})
export class Child3Component {
@Input() text = '';
}
@Component({
standalone: true,
selector: 'input-comp',
template: '<input [(ngModel)]="name">',
imports: [FormsModule],
})
export class InputComponent {
name = 'John';
}
/* Prefer this metadata syntax */
// @Directive({
// selector: 'input[value]',
// host: {
// '[value]': 'value',
// '(input)': 'valueChange.emit($event.target.value)'
// },
// inputs: ['value'],
// outputs: ['valueChange']
// })
// export class InputValueBinderDirective {
// value: any;
// valueChange: EventEmitter<any> = new EventEmitter();
// }
// As the styleguide recommends
@Directive({standalone: true, selector: 'input[value]'})
export class InputValueBinderDirective {
@HostBinding() @Input() value: any;
@Output() valueChange: EventEmitter<any> = new EventEmitter();
@HostListener('input', ['$event.target.value'])
onInput(value: any) {
this.valueChange.emit(value);
}
}
@Component({
standalone: true,
selector: 'input-value-comp',
template: ` Name: <input [value]="name" /> {{ name }} `,
})
export class InputValueBinderComponent {
name = 'Sally'; // initial value
}
@Component({
standalone: true,
selector: 'parent-comp',
imports: [Child1Component],
template: 'Parent(<child-1></child-1>)',
})
export class ParentComponent {}
@Component({
standalone: true,
selector: 'io-comp',
template: '<button type="button" class="hero" (click)="click()">Original {{hero.name}}</button>',
})
export class IoComponent {
@Input() hero!: Hero;
@Output() selected = new EventEmitter<Hero>();
click() {
this.selected.emit(this.hero);
}
}
@Component({
standalone: true,
selector: 'io-parent-comp',
template: `
@if (!selectedHero) {
<p><i>Click to select a hero</i></p>
}
@if (selectedHero) {
<p>The selected hero is {{ selectedHero.name }}</p>
}
@for (hero of heroes; track hero) {
<io-comp [hero]="hero" (selected)="onSelect($event)"> </io-comp>
}
`,
imports: [IoComponent, sharedImports],
})
export class IoParentComponent {
heroes: Hero[] = [{name: 'Bob'}, {name: 'Carol'}, {name: 'Ted'}, {name: 'Alice'}];
selectedHero!: Hero;
onSelect(hero: Hero) {
this.selectedHero = hero;
}
}
@Component({
standalone: true,
selector: 'my-if-comp',
template: 'MyIf(@if (showMore) {<span>More</span>})',
imports: [sharedImports],
})
export class MyIfComponent {
showMore = false;
}
@Component({
standalone: true,
selector: 'my-service-comp',
template: 'injected value: {{valueService.value}}',
providers: [ValueService],
})
export class TestProvidersComponent {
constructor(public valueService: ValueService) {}
}
@Component({
standalone: true,
selector: 'my-service-comp',
template: 'injected value: {{valueService.value}}',
viewProviders: [ValueService],
})
export class TestViewProvidersComponent {
constructor(public valueService: ValueService) {}
}
@Component({
standalone: true,
selector: 'external-template-comp',
templateUrl: './demo-external-template.html',
})
export class ExternalTemplateComponent implements OnInit {
serviceValue = '';
constructor(@Optional() private service?: ValueService) {}
ngOnInit() {
if (this.service) {
this.serviceValue = this.service.getValue();
}
}
}
@Component({
standalone: true,
selector: 'comp-w-ext-comp',
imports: [ExternalTemplateComponent],
template: `
<h3>comp-w-ext-comp</h3>
<external-template-comp></external-template-comp>
`,
})
export class InnerCompWithExternalTemplateComponent {}
@Component({standalone: true, selector: 'needs-content', template: '<ng-content></ng-content>'})
export class NeedsContentComponent {
// children with #content local variable
@ContentChildren('content') children: any;
}
///////// MyIfChildComp //////// | {
"end_byte": 7254,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo.ts_7255_11459 | @Component({
standalone: true,
selector: 'my-if-child-1',
template: ` <h4>MyIfChildComp</h4>
<div>
<label for="child-value"
>Child value: <input id="child-value" [(ngModel)]="childValue" />
</label>
</div>
<p><i>Change log:</i></p>
@for (log of changeLog; track log; let i = $index) {
<div>{{ i + 1 }} - {{ log }}</div>
}`,
imports: [FormsModule, sharedImports],
})
export class MyIfChildComponent implements OnInit, OnChanges, OnDestroy {
@Input() value = '';
@Output() valueChange = new EventEmitter<string>();
get childValue() {
return this.value;
}
set childValue(v: string) {
if (this.value === v) {
return;
}
this.value = v;
this.valueChange.emit(v);
}
changeLog: string[] = [];
ngOnInitCalled = false;
ngOnChangesCounter = 0;
ngOnDestroyCalled = false;
ngOnInit() {
this.ngOnInitCalled = true;
this.changeLog.push('ngOnInit called');
}
ngOnDestroy() {
this.ngOnDestroyCalled = true;
this.changeLog.push('ngOnDestroy called');
}
ngOnChanges(changes: SimpleChanges) {
for (const propName in changes) {
this.ngOnChangesCounter += 1;
const prop = changes[propName];
const cur = JSON.stringify(prop.currentValue);
const prev = JSON.stringify(prop.previousValue);
this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
}
}
}
///////// MyIfParentComp ////////
@Component({
standalone: true,
selector: 'my-if-parent-comp',
template: `
<h3>MyIfParentComp</h3>
<label for="parent"
>Parent value:
<input id="parent" [(ngModel)]="parentValue" />
</label>
<button type="button" (click)="clicked()">{{ toggleLabel }} Child</button><br />
@if (showChild) {
<div style="margin: 4px; padding: 4px; background-color: aliceblue;">
<my-if-child-1 [(value)]="parentValue"></my-if-child-1>
</div>
}
`,
imports: [FormsModule, MyIfChildComponent, sharedImports],
})
export class MyIfParentComponent implements OnInit {
ngOnInitCalled = false;
parentValue = 'Hello, World';
showChild = false;
toggleLabel = 'Unknown';
ngOnInit() {
this.ngOnInitCalled = true;
this.clicked();
}
clicked() {
this.showChild = !this.showChild;
this.toggleLabel = this.showChild ? 'Close' : 'Show';
}
}
@Component({
standalone: true,
selector: 'reverse-pipe-comp',
template: `
<input [(ngModel)]="text" />
<span>{{ text | reverse }}</span>
`,
imports: [ReversePipe, FormsModule],
})
export class ReversePipeComponent {
text = 'my dog has fleas.';
}
@Component({
standalone: true,
imports: [NeedsContentComponent],
template: '<div>Replace Me</div>',
})
export class ShellComponent {}
@Component({
standalone: true,
selector: 'demo-comp',
template: `
<h1>Specs Demo</h1>
<my-if-parent-comp></my-if-parent-comp>
<hr />
<h3>Input/Output Component</h3>
<io-parent-comp></io-parent-comp>
<hr />
<h3>External Template Component</h3>
<external-template-comp></external-template-comp>
<hr />
<h3>Component With External Template Component</h3>
<comp-w-ext-comp></comp-w-ext-comp>
<hr />
<h3>Reverse Pipe</h3>
<reverse-pipe-comp></reverse-pipe-comp>
<hr />
<h3>InputValueBinder Directive</h3>
<input-value-comp></input-value-comp>
<hr />
<h3>Button Component</h3>
<lightswitch-comp></lightswitch-comp>
<hr />
<h3>Needs Content</h3>
<needs-content #nc>
<child-1 #content text="My"></child-1>
<child-2 #content text="dog"></child-2>
<child-2 text="has"></child-2>
<child-3 #content text="fleas"></child-3>
<div #content>!</div>
</needs-content>
`,
imports: [
Child1Component,
Child2Component,
Child3Component,
ExternalTemplateComponent,
InnerCompWithExternalTemplateComponent,
InputValueBinderComponent,
IoParentComponent,
LightswitchComponent,
NeedsContentComponent,
ReversePipeComponent,
MyIfParentComponent,
],
})
export class DemoComponent {}
//////// Aggregations ////////////
export const demoProviders = [MasterService, ValueService]; | {
"end_byte": 11459,
"start_byte": 7255,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo-main.ts_0_188 | // main app entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {DemoModule} from './demo';
platformBrowserDynamic().bootstrapModule(DemoModule);
| {
"end_byte": 188,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo-main.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts_0_5172 | // #docplaster
import {Component, DebugElement, Injectable} from '@angular/core';
import {
ComponentFixture,
fakeAsync,
inject,
TestBed,
tick,
waitForAsync,
} from '@angular/core/testing';
import {FormsModule, NgControl, NgModel} from '@angular/forms';
import {By} from '@angular/platform-browser';
import {addMatchers, click} from '../../testing';
import {
BankAccountComponent,
BankAccountParentComponent,
Child1Component,
Child2Component,
Child3Component,
ExternalTemplateComponent,
InputComponent,
IoComponent,
IoParentComponent,
LightswitchComponent,
MasterService,
MyIfChildComponent,
MyIfComponent,
MyIfParentComponent,
NeedsContentComponent,
ParentComponent,
ReversePipeComponent,
ShellComponent,
TestProvidersComponent,
TestViewProvidersComponent,
ValueService,
} from './demo';
export class NotProvided extends ValueService {
/* example below */
}
beforeEach(addMatchers);
describe('demo (with TestBed):', () => {
//////// Service Tests /////////////
describe('ValueService', () => {
// #docregion value-service-before-each
let service: ValueService;
// #docregion value-service-inject-before-each
beforeEach(() => {
TestBed.configureTestingModule({providers: [ValueService]});
// #enddocregion value-service-before-each
service = TestBed.inject(ValueService);
// #docregion value-service-before-each
});
// #enddocregion value-service-before-each, value-service-inject-before-each
// #docregion value-service-inject-it
it('should use ValueService', () => {
service = TestBed.inject(ValueService);
expect(service.getValue()).toBe('real value');
});
// #enddocregion value-service-inject-it
it('can inject a default value when service is not provided', () => {
// #docregion testbed-get-w-null
expect(TestBed.inject(NotProvided, null)).toBeNull();
// #enddocregion testbed-get-w-null
});
it('test should wait for ValueService.getPromiseValue', waitForAsync(() => {
service.getPromiseValue().then((value) => expect(value).toBe('promise value'));
}));
it('test should wait for ValueService.getObservableValue', waitForAsync(() => {
service.getObservableValue().subscribe((value) => expect(value).toBe('observable value'));
}));
// Must use done. See https://github.com/angular/angular/issues/10127
it('test should wait for ValueService.getObservableDelayValue', (done: DoneFn) => {
service.getObservableDelayValue().subscribe((value) => {
expect(value).toBe('observable delay value');
done();
});
});
it('should allow the use of fakeAsync', fakeAsync(() => {
let value: any;
service.getPromiseValue().then((val: any) => (value = val));
tick(); // Trigger JS engine cycle until all promises resolve.
expect(value).toBe('promise value');
}));
});
describe('MasterService', () => {
// #docregion master-service-before-each
let masterService: MasterService;
let valueServiceSpy: jasmine.SpyObj<ValueService>;
beforeEach(() => {
const spy = jasmine.createSpyObj('ValueService', ['getValue']);
TestBed.configureTestingModule({
// Provide both the service-to-test and its (spy) dependency
providers: [MasterService, {provide: ValueService, useValue: spy}],
});
// Inject both the service-to-test and its (spy) dependency
masterService = TestBed.inject(MasterService);
valueServiceSpy = TestBed.inject(ValueService) as jasmine.SpyObj<ValueService>;
});
// #enddocregion master-service-before-each
// #docregion master-service-it
it('#getValue should return stubbed value from a spy', () => {
const stubValue = 'stub value';
valueServiceSpy.getValue.and.returnValue(stubValue);
expect(masterService.getValue()).withContext('service returned stub value').toBe(stubValue);
expect(valueServiceSpy.getValue.calls.count())
.withContext('spy method was called once')
.toBe(1);
expect(valueServiceSpy.getValue.calls.mostRecent().returnValue).toBe(stubValue);
});
// #enddocregion master-service-it
});
describe('use inject within `it`', () => {
beforeEach(() => {
TestBed.configureTestingModule({providers: [ValueService]});
});
it('should use modified providers', inject([ValueService], (service: ValueService) => {
service.setValue('value modified in beforeEach');
expect(service.getValue()).toBe('value modified in beforeEach');
}));
});
describe('using waitForAsync(inject) within beforeEach', () => {
let serviceValue: string;
beforeEach(() => {
TestBed.configureTestingModule({providers: [ValueService]});
});
beforeEach(waitForAsync(
inject([ValueService], (service: ValueService) => {
service.getPromiseValue().then((value) => (serviceValue = value));
}),
));
it('should use asynchronously modified value ... in synchronous test', () => {
expect(serviceValue).toBe('promise value');
});
});
/////////// Component Tests ////////////////// | {
"end_byte": 5172,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts_5176_14498 | describe('TestBed component tests', () => {
// beforeEach(waitForAsync(() => {
// TestBed.configureTestingModule()
// // Compile everything in DemoModule
// .compileComponents();
// }));
it('should create a component with inline template', () => {
const fixture = TestBed.createComponent(Child1Component);
fixture.detectChanges();
expect(fixture).toHaveText('Child');
});
it('should create a component with external template', () => {
const fixture = TestBed.createComponent(ExternalTemplateComponent);
fixture.detectChanges();
expect(fixture).toHaveText('from external template');
});
it('should allow changing members of the component', () => {
const fixture = TestBed.createComponent(MyIfComponent);
fixture.detectChanges();
expect(fixture).toHaveText('MyIf()');
fixture.componentInstance.showMore = true;
fixture.detectChanges();
expect(fixture).toHaveText('MyIf(More)');
});
it('should create a nested component bound to inputs/outputs', () => {
const fixture = TestBed.createComponent(IoParentComponent);
fixture.detectChanges();
const heroes = fixture.debugElement.queryAll(By.css('.hero'));
expect(heroes.length).withContext('has heroes').toBeGreaterThan(0);
const comp = fixture.componentInstance;
const hero = comp.heroes[0];
click(heroes[0]);
fixture.detectChanges();
const selected = fixture.debugElement.query(By.css('p'));
expect(selected).toHaveText(hero.name);
});
it('can access the instance variable of an `*ngFor` row component', () => {
const fixture = TestBed.createComponent(IoParentComponent);
const comp = fixture.componentInstance;
const heroName = comp.heroes[0].name; // first hero's name
fixture.detectChanges();
const ngForRow = fixture.debugElement.query(By.directive(IoComponent)); // first hero ngForRow
const hero = ngForRow.context.hero; // the hero object passed into the row
expect(hero.name).withContext('ngRow.context.hero').toBe(heroName);
const rowComp = ngForRow.componentInstance;
// jasmine.any is an "instance-of-type" test.
expect(rowComp).withContext('component is IoComp').toEqual(jasmine.any(IoComponent));
expect(rowComp.hero.name).withContext('component.hero').toBe(heroName);
});
it('should support clicking a button', () => {
const fixture = TestBed.createComponent(LightswitchComponent);
const btn = fixture.debugElement.query(By.css('button'));
const span = fixture.debugElement.query(By.css('span')).nativeElement;
fixture.detectChanges();
expect(span.textContent)
.withContext('before click')
.toMatch(/is off/i);
click(btn);
fixture.detectChanges();
expect(span.textContent).withContext('after click').toMatch(/is on/i);
});
// ngModel is async so we must wait for it with promise-based `whenStable`
it('should support entering text in input box (ngModel)', waitForAsync(() => {
const expectedOrigName = 'John';
const expectedNewName = 'Sally';
const fixture = TestBed.createComponent(InputComponent);
fixture.detectChanges();
const comp = fixture.componentInstance;
const input = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
expect(comp.name)
.withContext(`At start name should be ${expectedOrigName} `)
.toBe(expectedOrigName);
// wait until ngModel binds comp.name to input box
fixture
.whenStable()
.then(() => {
expect(input.value)
.withContext(
`After ngModel updates input box, input.value should be ${expectedOrigName} `,
)
.toBe(expectedOrigName);
// simulate user entering new name in input
input.value = expectedNewName;
// that change doesn't flow to the component immediately
expect(comp.name)
.withContext(
`comp.name should still be ${expectedOrigName} after value change, before binding happens`,
)
.toBe(expectedOrigName);
// Dispatch a DOM event so that Angular learns of input value change.
// then wait while ngModel pushes input.box value to comp.name
input.dispatchEvent(new Event('input'));
return fixture.whenStable();
})
.then(() => {
expect(comp.name)
.withContext(`After ngModel updates the model, comp.name should be ${expectedNewName} `)
.toBe(expectedNewName);
});
}));
// fakeAsync version of ngModel input test enables sync test style
// synchronous `tick` replaces asynchronous promise-base `whenStable`
it('should support entering text in input box (ngModel) - fakeAsync', fakeAsync(() => {
const expectedOrigName = 'John';
const expectedNewName = 'Sally';
const fixture = TestBed.createComponent(InputComponent);
fixture.detectChanges();
const comp = fixture.componentInstance;
const input = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
expect(comp.name)
.withContext(`At start name should be ${expectedOrigName} `)
.toBe(expectedOrigName);
// wait until ngModel binds comp.name to input box
tick();
expect(input.value)
.withContext(`After ngModel updates input box, input.value should be ${expectedOrigName} `)
.toBe(expectedOrigName);
// simulate user entering new name in input
input.value = expectedNewName;
// that change doesn't flow to the component immediately
expect(comp.name)
.withContext(
`comp.name should still be ${expectedOrigName} after value change, before binding happens`,
)
.toBe(expectedOrigName);
// Dispatch a DOM event so that Angular learns of input value change.
// then wait a tick while ngModel pushes input.box value to comp.name
input.dispatchEvent(new Event('input'));
tick();
expect(comp.name)
.withContext(`After ngModel updates the model, comp.name should be ${expectedNewName} `)
.toBe(expectedNewName);
}));
it('ReversePipeComp should reverse the input text', fakeAsync(() => {
const inputText = 'the quick brown fox.';
const expectedText = '.xof nworb kciuq eht';
const fixture = TestBed.createComponent(ReversePipeComponent);
fixture.detectChanges();
const comp = fixture.componentInstance;
const input = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
const span = fixture.debugElement.query(By.css('span')).nativeElement as HTMLElement;
// simulate user entering new name in input
input.value = inputText;
// Dispatch a DOM event so that Angular learns of input value change.
// then wait a tick while ngModel pushes input.box value to comp.text
// and Angular updates the output span
input.dispatchEvent(new Event('input'));
tick();
fixture.detectChanges();
expect(span.textContent).withContext('output span').toBe(expectedText);
expect(comp.text).withContext('component.text').toBe(inputText);
}));
// Use this technique to find attached directives of any kind
it('can examine attached directives and listeners', () => {
const fixture = TestBed.createComponent(InputComponent);
fixture.detectChanges();
const inputEl = fixture.debugElement.query(By.css('input'));
expect(inputEl.providerTokens).withContext('NgModel directive').toContain(NgModel);
const ngControl = inputEl.injector.get(NgControl);
expect(ngControl).withContext('NgControl directive').toEqual(jasmine.any(NgControl));
expect(inputEl.listeners.length).withContext('several listeners attached').toBeGreaterThan(2);
});
it('BankAccountComponent should set attributes, styles, classes, and properties', () => {
const fixture = TestBed.createComponent(BankAccountParentComponent);
fixture.detectChanges();
const comp = fixture.componentInstance;
// the only child is debugElement of the BankAccount component
const el = fixture.debugElement.children[0];
const childComp = el.componentInstance as BankAccountComponent;
expect(childComp).toEqual(jasmine.any(BankAccountComponent));
expect(el.context).withContext('context is the child component').toBe(childComp);
expect(el.attributes['account']).withContext('account attribute').toBe(childComp.id);
expect(el.attributes['bank']).withContext('bank attribute').toBe(childComp.bank);
expect(el.classes['closed']).withContext('closed class').toBe(true);
expect(el.classes['open']).withContext('open class').toBeFalsy();
expect(el.styles['color']).withContext('color style').toBe(comp.color);
expect(el.styles['width'])
.withContext('width style')
.toBe(comp.width + 'px');
// Removed on 12/02/2016 when ceased public discussion of the `Renderer`. Revive in future?
// expect(el.properties['customProperty']).toBe(true, 'customProperty');
});
}); | {
"end_byte": 14498,
"start_byte": 5176,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts_14502_21328 | describe('TestBed component overrides:', () => {
it("should override ChildComp's template", () => {
const fixture = TestBed.configureTestingModule({
imports: [Child1Component],
})
.overrideComponent(Child1Component, {
set: {template: '<span>Fake</span>'},
})
.createComponent(Child1Component);
fixture.detectChanges();
expect(fixture).toHaveText('Fake');
});
it("should override TestProvidersComp's ValueService provider", () => {
const fixture = TestBed.configureTestingModule({
imports: [TestProvidersComponent],
})
.overrideComponent(TestProvidersComponent, {
remove: {providers: [ValueService]},
add: {providers: [{provide: ValueService, useClass: FakeValueService}]},
// Or replace them all (this component has only one provider)
// set: { providers: [{ provide: ValueService, useClass: FakeValueService }] },
})
.createComponent(TestProvidersComponent);
fixture.detectChanges();
expect(fixture).toHaveText('injected value: faked value', 'text');
// Explore the providerTokens
const tokens = fixture.debugElement.providerTokens;
expect(tokens).withContext('component ctor').toContain(fixture.componentInstance.constructor);
expect(tokens).withContext('TestProvidersComp').toContain(TestProvidersComponent);
expect(tokens).withContext('ValueService').toContain(ValueService);
});
it("should override TestViewProvidersComp's ValueService viewProvider", () => {
const fixture = TestBed.configureTestingModule({
imports: [TestViewProvidersComponent],
})
.overrideComponent(TestViewProvidersComponent, {
// remove: { viewProviders: [ValueService]},
// add: { viewProviders: [{ provide: ValueService, useClass: FakeValueService }]
// },
// Or replace them all (this component has only one viewProvider)
set: {viewProviders: [{provide: ValueService, useClass: FakeValueService}]},
})
.createComponent(TestViewProvidersComponent);
fixture.detectChanges();
expect(fixture).toHaveText('injected value: faked value');
});
it("injected provider should not be same as component's provider", () => {
// TestComponent is parent of TestProvidersComponent
@Component({
standalone: true,
template: '<my-service-comp></my-service-comp>',
imports: [TestProvidersComponent],
})
class TestComponent {}
// 3 levels of ValueService provider: module, TestComponent, TestProvidersComponent
const fixture = TestBed.configureTestingModule({
imports: [TestComponent, TestProvidersComponent],
providers: [ValueService],
})
.overrideComponent(TestComponent, {
set: {providers: [{provide: ValueService, useValue: {}}]},
})
.overrideComponent(TestProvidersComponent, {
set: {providers: [{provide: ValueService, useClass: FakeValueService}]},
})
.createComponent(TestComponent);
let testBedProvider!: ValueService;
// `inject` uses TestBed's injector
inject([ValueService], (s: ValueService) => (testBedProvider = s))();
const tcProvider = fixture.debugElement.injector.get(ValueService) as ValueService;
const tpcProvider = fixture.debugElement.children[0].injector.get(
ValueService,
) as FakeValueService;
expect(testBedProvider).withContext('testBed/tc not same providers').not.toBe(tcProvider);
expect(testBedProvider).withContext('testBed/tpc not same providers').not.toBe(tpcProvider);
expect(testBedProvider instanceof ValueService)
.withContext('testBedProvider is ValueService')
.toBe(true);
expect(tcProvider)
.withContext('tcProvider is {}')
.toEqual({} as ValueService);
expect(tpcProvider instanceof FakeValueService)
.withContext('tpcProvider is FakeValueService')
.toBe(true);
});
it('can access template local variables as references', () => {
const fixture = TestBed.configureTestingModule({
imports: [
ShellComponent,
NeedsContentComponent,
Child1Component,
Child2Component,
Child3Component,
],
})
.overrideComponent(ShellComponent, {
set: {
selector: 'test-shell',
imports: [NeedsContentComponent, Child1Component, Child2Component, Child3Component],
template: `
<needs-content #nc>
<child-1 #content text="My"></child-1>
<child-2 #content text="dog"></child-2>
<child-2 text="has"></child-2>
<child-3 #content text="fleas"></child-3>
<div #content>!</div>
</needs-content>
`,
},
})
.createComponent(ShellComponent);
fixture.detectChanges();
// NeedsContentComp is the child of ShellComp
const el = fixture.debugElement.children[0];
const comp = el.componentInstance;
expect(comp.children.toArray().length)
.withContext('three different child components and an ElementRef with #content')
.toBe(4);
expect(el.references['nc']).withContext('#nc reference to component').toBe(comp);
// #docregion custom-predicate
// Filter for DebugElements with a #content reference
const contentRefs = el.queryAll((de) => de.references['content']);
// #enddocregion custom-predicate
expect(contentRefs.length).withContext('elements w/ a #content reference').toBe(4);
});
});
describe('nested (one-deep) component override', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ParentComponent, FakeChildComponent],
}).overrideComponent(ParentComponent, {
set: {imports: [FakeChildComponent]},
});
});
it('ParentComp should use Fake Child component', () => {
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(fixture).toHaveText('Parent(Fake Child)');
});
});
describe('nested (two-deep) component override', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ParentComponent, FakeChildWithGrandchildComponent, FakeGrandchildComponent],
}).overrideComponent(ParentComponent, {
set: {imports: [FakeChildWithGrandchildComponent, FakeGrandchildComponent]},
});
});
it('should use Fake Grandchild component', () => {
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(fixture).toHaveText('Parent(Fake Child(Fake Grandchild))');
});
}); | {
"end_byte": 21328,
"start_byte": 14502,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts_21332_25817 | describe('lifecycle hooks w/ MyIfParentComp', () => {
let fixture: ComponentFixture<MyIfParentComponent>;
let parent: MyIfParentComponent;
let child: MyIfChildComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule, MyIfChildComponent, MyIfParentComponent],
});
fixture = TestBed.createComponent(MyIfParentComponent);
parent = fixture.componentInstance;
});
it('should instantiate parent component', () => {
expect(parent).withContext('parent component should exist').not.toBeNull();
});
it('parent component OnInit should NOT be called before first detectChanges()', () => {
expect(parent.ngOnInitCalled).toBe(false);
});
it('parent component OnInit should be called after first detectChanges()', () => {
fixture.detectChanges();
expect(parent.ngOnInitCalled).toBe(true);
});
it('child component should exist after OnInit', () => {
fixture.detectChanges();
getChild();
expect(child instanceof MyIfChildComponent)
.withContext('should create child')
.toBe(true);
});
it("should have called child component's OnInit ", () => {
fixture.detectChanges();
getChild();
expect(child.ngOnInitCalled).toBe(true);
});
it('child component called OnChanges once', () => {
fixture.detectChanges();
getChild();
expect(child.ngOnChangesCounter).toBe(1);
});
it('changed parent value flows to child', () => {
fixture.detectChanges();
getChild();
parent.parentValue = 'foo';
fixture.detectChanges();
expect(child.ngOnChangesCounter)
.withContext('expected 2 changes: initial value and changed value')
.toBe(2);
expect(child.childValue).withContext('childValue should eq changed parent value').toBe('foo');
});
// must be async test to see child flow to parent
it('changed child value flows to parent', waitForAsync(() => {
fixture.detectChanges();
getChild();
child.childValue = 'bar';
return new Promise<void>((resolve) => {
// Wait one JS engine turn!
setTimeout(() => resolve(), 0);
}).then(() => {
fixture.detectChanges();
expect(child.ngOnChangesCounter)
.withContext('expected 2 changes: initial value and changed value')
.toBe(2);
expect(parent.parentValue)
.withContext('parentValue should eq changed parent value')
.toBe('bar');
});
}));
it('clicking "Close Child" triggers child OnDestroy', () => {
fixture.detectChanges();
getChild();
const btn = fixture.debugElement.query(By.css('button'));
click(btn);
fixture.detectChanges();
expect(child.ngOnDestroyCalled).toBe(true);
});
////// helpers ///
/**
* Get the MyIfChildComp from parent; fail w/ good message if cannot.
*/
function getChild() {
let childDe: DebugElement; // DebugElement that should hold the MyIfChildComp
// The Hard Way: requires detailed knowledge of the parent template
try {
childDe = fixture.debugElement.children[4].children[0];
} catch (err) {
/* we'll report the error */
}
// DebugElement.queryAll: if we wanted all of many instances:
childDe = fixture.debugElement.queryAll(
(de) => de.componentInstance instanceof MyIfChildComponent,
)[0];
// WE'LL USE THIS APPROACH !
// DebugElement.query: find first instance (if any)
childDe = fixture.debugElement.query(
(de) => de.componentInstance instanceof MyIfChildComponent,
);
if (childDe && childDe.componentInstance) {
child = childDe.componentInstance;
} else {
fail('Unable to find MyIfChildComp within MyIfParentComp');
}
return child;
}
});
});
////////// Fakes ///////////
@Component({
standalone: true,
selector: 'child-1',
template: 'Fake Child',
})
class FakeChildComponent {}
@Component({
standalone: true,
selector: 'grandchild-1',
template: 'Fake Grandchild',
})
class FakeGrandchildComponent {}
@Component({
standalone: true,
selector: 'child-1',
imports: [FakeGrandchildComponent],
template: 'Fake Child(<grandchild-1></grandchild-1>)',
})
class FakeChildWithGrandchildComponent {}
@Injectable()
class FakeValueService extends ValueService {
override value = 'faked value';
} | {
"end_byte": 25817,
"start_byte": 21332,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts_0_6420 | import {fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {interval, of} from 'rxjs';
import {delay, take} from 'rxjs/operators';
describe('Angular async helper', () => {
describe('async', () => {
let actuallyDone = false;
beforeEach(() => {
actuallyDone = false;
});
afterEach(() => {
expect(actuallyDone).withContext('actuallyDone should be true').toBe(true);
});
it('should run normal test', () => {
actuallyDone = true;
});
it('should run normal async test', (done: DoneFn) => {
setTimeout(() => {
actuallyDone = true;
done();
}, 0);
});
it('should run async test with task', waitForAsync(() => {
setTimeout(() => {
actuallyDone = true;
}, 0);
}));
it('should run async test with task', waitForAsync(() => {
const id = setInterval(() => {
actuallyDone = true;
clearInterval(id);
}, 100);
}));
it('should run async test with successful promise', waitForAsync(() => {
const p = new Promise((resolve) => {
setTimeout(resolve, 10);
});
p.then(() => {
actuallyDone = true;
});
}));
it('should run async test with failed promise', waitForAsync(() => {
const p = new Promise((resolve, reject) => {
setTimeout(reject, 10);
});
p.catch(() => {
actuallyDone = true;
});
}));
// Use done. Can also use async or fakeAsync.
it('should run async test with successful delayed Observable', (done: DoneFn) => {
const source = of(true).pipe(delay(10));
source.subscribe({
next: (val) => (actuallyDone = true),
error: (err) => fail(err),
complete: done,
});
});
it('should run async test with successful delayed Observable', waitForAsync(() => {
const source = of(true).pipe(delay(10));
source.subscribe({
next: (val) => (actuallyDone = true),
error: (err) => fail(err),
});
}));
it('should run async test with successful delayed Observable', fakeAsync(() => {
const source = of(true).pipe(delay(10));
source.subscribe({
next: (val) => (actuallyDone = true),
error: (err) => fail(err),
});
tick(10);
}));
});
describe('fakeAsync', () => {
// #docregion fake-async-test-tick
it('should run timeout callback with delay after call tick with millis', fakeAsync(() => {
let called = false;
setTimeout(() => {
called = true;
}, 100);
tick(100);
expect(called).toBe(true);
}));
// #enddocregion fake-async-test-tick
// #docregion fake-async-test-tick-new-macro-task-sync
it('should run new macro task callback with delay after call tick with millis', fakeAsync(() => {
function nestedTimer(cb: () => any): void {
setTimeout(() => setTimeout(() => cb()));
}
const callback = jasmine.createSpy('callback');
nestedTimer(callback);
expect(callback).not.toHaveBeenCalled();
tick(0);
// the nested timeout will also be triggered
expect(callback).toHaveBeenCalled();
}));
// #enddocregion fake-async-test-tick-new-macro-task-sync
// #docregion fake-async-test-tick-new-macro-task-async
it('should not run new macro task callback with delay after call tick with millis', fakeAsync(() => {
function nestedTimer(cb: () => any): void {
setTimeout(() => setTimeout(() => cb()));
}
const callback = jasmine.createSpy('callback');
nestedTimer(callback);
expect(callback).not.toHaveBeenCalled();
tick(0, {processNewMacroTasksSynchronously: false});
// the nested timeout will not be triggered
expect(callback).not.toHaveBeenCalled();
tick(0);
expect(callback).toHaveBeenCalled();
}));
// #enddocregion fake-async-test-tick-new-macro-task-async
// #docregion fake-async-test-date
it('should get Date diff correctly in fakeAsync', fakeAsync(() => {
const start = Date.now();
tick(100);
const end = Date.now();
expect(end - start).toBe(100);
}));
// #enddocregion fake-async-test-date
// #docregion fake-async-test-rxjs
it('should get Date diff correctly in fakeAsync with rxjs scheduler', fakeAsync(() => {
// need to add `import 'zone.js/plugins/zone-patch-rxjs-fake-async'
// to patch rxjs scheduler
let result = '';
of('hello')
.pipe(delay(1000))
.subscribe((v) => {
result = v;
});
expect(result).toBe('');
tick(1000);
expect(result).toBe('hello');
const start = new Date().getTime();
let dateDiff = 0;
interval(1000)
.pipe(take(2))
.subscribe(() => (dateDiff = new Date().getTime() - start));
tick(1000);
expect(dateDiff).toBe(1000);
tick(1000);
expect(dateDiff).toBe(2000);
}));
// #enddocregion fake-async-test-rxjs
});
// #docregion fake-async-test-clock
describe('use jasmine.clock()', () => {
// need to config __zone_symbol__fakeAsyncPatchLock flag
// before loading zone.js/testing
beforeEach(() => {
jasmine.clock().install();
});
afterEach(() => {
jasmine.clock().uninstall();
});
it('should auto enter fakeAsync', () => {
// is in fakeAsync now, don't need to call fakeAsync(testFn)
let called = false;
setTimeout(() => {
called = true;
}, 100);
jasmine.clock().tick(100);
expect(called).toBe(true);
});
});
// #enddocregion fake-async-test-clock
describe('test jsonp', () => {
function jsonp(url: string, callback: () => void) {
// do a jsonp call which is not zone aware
}
// need to config __zone_symbol__supportWaitUnResolvedChainedPromise flag
// before loading zone.js/testing
it('should wait until promise.then is called', waitForAsync(() => {
let finished = false;
new Promise<void>((res) => {
jsonp('localhost:8080/jsonp', () => {
// success callback and resolve the promise
finished = true;
res();
});
}).then(() => {
// async will wait until promise.then is called
// if __zone_symbol__supportWaitUnResolvedChainedPromise is set
expect(finished).toBe(true);
});
}));
});
});
| {
"end_byte": 6420,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/demo/demo-external-template.html_0_36 | <span>from external template</span>
| {
"end_byte": 36,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/demo/demo-external-template.html"
} |
angular/adev/src/content/examples/testing/src/app/shared/highlight.directive.ts_0_670 | /* eslint-disable @angular-eslint/directive-selector */
// #docregion
import {Directive, ElementRef, Input, OnChanges} from '@angular/core';
@Directive({standalone: true, selector: '[highlight]'})
/**
* Set backgroundColor for the attached element to highlight color
* and set the element's customProperty to true
*/
export class HighlightDirective implements OnChanges {
defaultColor = 'rgb(211, 211, 211)'; // lightgray
@Input('highlight') bgColor = '';
constructor(private el: ElementRef) {
el.nativeElement.style.customProperty = true;
}
ngOnChanges() {
this.el.nativeElement.style.backgroundColor = this.bgColor || this.defaultColor;
}
}
| {
"end_byte": 670,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/shared/highlight.directive.ts"
} |
angular/adev/src/content/examples/testing/src/app/shared/canvas.component.spec.ts_0_1085 | // #docplaster
// #docregion without-toBlob-macrotask
import {fakeAsync, TestBed, tick} from '@angular/core/testing';
import {CanvasComponent} from './canvas.component';
describe('CanvasComponent', () => {
// #enddocregion without-toBlob-macrotask
// #docregion enable-toBlob-macrotask
beforeEach(() => {
(window as any).__zone_symbol__FakeAsyncTestMacroTask = [
{
source: 'HTMLCanvasElement.toBlob',
callbackArgs: [{size: 200}],
},
];
});
// #enddocregion enable-toBlob-macrotask
// #docregion without-toBlob-macrotask
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CanvasComponent],
}).compileComponents();
});
it('should be able to generate blob data from canvas', fakeAsync(() => {
const fixture = TestBed.createComponent(CanvasComponent);
const canvasComp = fixture.componentInstance;
fixture.detectChanges();
expect(canvasComp.blobSize).toBe(0);
tick();
expect(canvasComp.blobSize).toBeGreaterThan(0);
}));
});
// #enddocregion without-toBlob-macrotask
| {
"end_byte": 1085,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/shared/canvas.component.spec.ts"
} |
angular/adev/src/content/examples/testing/src/app/shared/title-case.pipe.spec.ts_0_923 | // #docplaster
// #docregion
import {TitleCasePipe} from './title-case.pipe';
// #docregion excerpt
describe('TitleCasePipe', () => {
// This pipe is a pure, stateless function so no need for BeforeEach
const pipe = new TitleCasePipe();
it('transforms "abc" to "Abc"', () => {
expect(pipe.transform('abc')).toBe('Abc');
});
it('transforms "abc def" to "Abc Def"', () => {
expect(pipe.transform('abc def')).toBe('Abc Def');
});
// ... more tests ...
// #enddocregion excerpt
it('leaves "Abc Def" unchanged', () => {
expect(pipe.transform('Abc Def')).toBe('Abc Def');
});
it('transforms "abc-def" to "Abc-def"', () => {
expect(pipe.transform('abc-def')).toBe('Abc-def');
});
it('transforms " abc def" to " Abc Def" (preserves spaces) ', () => {
expect(pipe.transform(' abc def')).toBe(' Abc Def');
});
// #docregion excerpt
});
// #enddocregion excerpt
| {
"end_byte": 923,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/examples/testing/src/app/shared/title-case.pipe.spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.