_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular/adev/src/content/api-examples/forms/ts/reactiveRadioButtons/module.ts_0_651 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {ReactiveFormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {ReactiveRadioButtonComp} from './reactive_radio_button_example';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [ReactiveRadioButtonComp],
bootstrap: [ReactiveRadioButtonComp],
})
export class AppModule {}
export {ReactiveRadioButtonComp as AppComponent};
| {
"end_byte": 651,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/reactiveRadioButtons/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts_0_878 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion Reactive
import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form">
<input type="radio" formControlName="food" value="beef" />
Beef
<input type="radio" formControlName="food" value="lamb" />
Lamb
<input type="radio" formControlName="food" value="fish" />
Fish
</form>
<p>Form value: {{ form.value | json }}</p>
<!-- {food: 'lamb' } -->
`,
standalone: false,
})
export class ReactiveRadioButtonComp {
form = new FormGroup({
food: new FormControl('lamb'),
});
}
// #enddocregion
| {
"end_byte": 878,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/reactiveRadioButtons/e2e_test/reactive_radio_button_spec.ts_0_1341 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementArrayFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('radioButtons example', () => {
afterEach(verifyNoBrowserErrors);
let inputs: ElementArrayFinder;
beforeEach(() => {
browser.get('/reactiveRadioButtons');
inputs = element.all(by.css('input'));
});
it('should populate the UI with initial values', () => {
expect(inputs.get(0).getAttribute('checked')).toEqual(null);
expect(inputs.get(1).getAttribute('checked')).toEqual('true');
expect(inputs.get(2).getAttribute('checked')).toEqual(null);
expect(element(by.css('p')).getText()).toEqual('Form value: { "food": "lamb" }');
});
it('update model and other buttons as the UI value changes', () => {
inputs.get(0).click();
expect(inputs.get(0).getAttribute('checked')).toEqual('true');
expect(inputs.get(1).getAttribute('checked')).toEqual(null);
expect(inputs.get(2).getAttribute('checked')).toEqual(null);
expect(element(by.css('p')).getText()).toEqual('Form value: { "food": "beef" }');
});
});
| {
"end_byte": 1341,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/reactiveRadioButtons/e2e_test/reactive_radio_button_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/formBuilder/module.ts_0_670 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {ReactiveFormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {DisabledFormControlComponent, FormBuilderComp} from './form_builder_example';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [FormBuilderComp, DisabledFormControlComponent],
bootstrap: [FormBuilderComp],
})
export class AppModule {}
export {FormBuilderComp as AppComponent};
| {
"end_byte": 670,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/formBuilder/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/formBuilder/form_builder_example.ts_0_1643 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion disabled-control
import {Component, Inject} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
// #enddocregion disabled-control
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form">
<div formGroupName="name">
<input formControlName="first" placeholder="First" />
<input formControlName="last" placeholder="Last" />
</div>
<input formControlName="email" placeholder="Email" />
<button>Submit</button>
</form>
<p>Value: {{ form.value | json }}</p>
<p>Validation status: {{ form.status }}</p>
`,
standalone: false,
})
export class FormBuilderComp {
form: FormGroup;
constructor(@Inject(FormBuilder) formBuilder: FormBuilder) {
this.form = formBuilder.group(
{
name: formBuilder.group({
first: ['Nancy', Validators.minLength(2)],
last: 'Drew',
}),
email: '',
},
{updateOn: 'change'},
);
}
}
// #docregion disabled-control
@Component({
selector: 'app-disabled-form-control',
template: `
<input [formControl]="control" placeholder="First" />
`,
standalone: false,
})
export class DisabledFormControlComponent {
control: FormControl;
constructor(private formBuilder: FormBuilder) {
this.control = formBuilder.control({value: 'my val', disabled: true});
}
}
// #enddocregion disabled-control
| {
"end_byte": 1643,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/formBuilder/form_builder_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/formBuilder/e2e_test/form_builder_spec.ts_0_1172 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementArrayFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('formBuilder example', () => {
afterEach(verifyNoBrowserErrors);
let inputs: ElementArrayFinder;
let paragraphs: ElementArrayFinder;
beforeEach(() => {
browser.get('/formBuilder');
inputs = element.all(by.css('input'));
paragraphs = element.all(by.css('p'));
});
it('should populate the UI with initial values', () => {
expect(inputs.get(0).getAttribute('value')).toEqual('Nancy');
expect(inputs.get(1).getAttribute('value')).toEqual('Drew');
});
it('should update the validation status', () => {
expect(paragraphs.get(1).getText()).toEqual('Validation status: VALID');
inputs.get(0).click();
inputs.get(0).clear();
inputs.get(0).sendKeys('a');
expect(paragraphs.get(1).getText()).toEqual('Validation status: INVALID');
});
});
| {
"end_byte": 1172,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/formBuilder/e2e_test/form_builder_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/nestedFormArray/module.ts_0_615 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {ReactiveFormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {NestedFormArray} from './nested_form_array_example';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [NestedFormArray],
bootstrap: [NestedFormArray],
})
export class AppModule {}
export {NestedFormArray as AppComponent};
| {
"end_byte": 615,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/nestedFormArray/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/nestedFormArray/nested_form_array_example.ts_0_1336 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* tslint:disable:no-console */
// #docregion Component
import {Component} from '@angular/core';
import {FormArray, FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div formArrayName="cities">
<div *ngFor="let city of cities.controls; index as i">
<input [formControlName]="i" placeholder="City" />
</div>
</div>
<button>Submit</button>
</form>
<button (click)="addCity()">Add City</button>
<button (click)="setPreset()">Set preset</button>
`,
standalone: false,
})
export class NestedFormArray {
form = new FormGroup({
cities: new FormArray([new FormControl('SF'), new FormControl('NY')]),
});
get cities(): FormArray {
return this.form.get('cities') as FormArray;
}
addCity() {
this.cities.push(new FormControl());
}
onSubmit() {
console.log(this.cities.value); // ['SF', 'NY']
console.log(this.form.value); // { cities: ['SF', 'NY'] }
}
setPreset() {
this.cities.patchValue(['LA', 'MTV']);
}
}
// #enddocregion
| {
"end_byte": 1336,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/nestedFormArray/nested_form_array_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/nestedFormArray/e2e_test/nested_form_array_spec.ts_0_1290 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementArrayFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('nestedFormArray example', () => {
afterEach(verifyNoBrowserErrors);
let inputs: ElementArrayFinder;
let buttons: ElementArrayFinder;
beforeEach(() => {
browser.get('/nestedFormArray');
inputs = element.all(by.css('input'));
buttons = element.all(by.css('button'));
});
it('should populate the UI with initial values', () => {
expect(inputs.get(0).getAttribute('value')).toEqual('SF');
expect(inputs.get(1).getAttribute('value')).toEqual('NY');
});
it('should add inputs programmatically', () => {
expect(inputs.count()).toBe(2);
buttons.get(1).click();
inputs = element.all(by.css('input'));
expect(inputs.count()).toBe(3);
});
it('should set the value programmatically', () => {
buttons.get(2).click();
expect(inputs.get(0).getAttribute('value')).toEqual('LA');
expect(inputs.get(1).getAttribute('value')).toEqual('MTV');
});
});
| {
"end_byte": 1290,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/nestedFormArray/e2e_test/nested_form_array_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleFormGroup/module.ts_0_615 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {ReactiveFormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {SimpleFormGroup} from './simple_form_group_example';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [SimpleFormGroup],
bootstrap: [SimpleFormGroup],
})
export class AppModule {}
export {SimpleFormGroup as AppComponent};
| {
"end_byte": 615,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleFormGroup/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleFormGroup/simple_form_group_example.ts_0_1221 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* tslint:disable:no-console */
// #docregion Component
import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div *ngIf="first.invalid">Name is too short.</div>
<input formControlName="first" placeholder="First name" />
<input formControlName="last" placeholder="Last name" />
<button type="submit">Submit</button>
</form>
<button (click)="setValue()">Set preset value</button>
`,
standalone: false,
})
export class SimpleFormGroup {
form = new FormGroup({
first: new FormControl('Nancy', Validators.minLength(2)),
last: new FormControl('Drew'),
});
get first(): any {
return this.form.get('first');
}
onSubmit(): void {
console.log(this.form.value); // {first: 'Nancy', last: 'Drew'}
}
setValue() {
this.form.setValue({first: 'Carson', last: 'Drew'});
}
}
// #enddocregion
| {
"end_byte": 1221,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleFormGroup/simple_form_group_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleFormGroup/e2e_test/simple_form_group_spec.ts_0_1459 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('formControlName example', () => {
afterEach(verifyNoBrowserErrors);
describe('index view', () => {
let firstInput: ElementFinder;
let lastInput: ElementFinder;
beforeEach(() => {
browser.get('/simpleFormGroup');
firstInput = element(by.css('[formControlName="first"]'));
lastInput = element(by.css('[formControlName="last"]'));
});
it('should populate the form control values in the DOM', () => {
expect(firstInput.getAttribute('value')).toEqual('Nancy');
expect(lastInput.getAttribute('value')).toEqual('Drew');
});
it('should show the error when the form is invalid', () => {
firstInput.click();
firstInput.clear();
firstInput.sendKeys('a');
expect(element(by.css('div')).getText()).toEqual('Name is too short.');
});
it('should set the value programmatically', () => {
element(by.css('button:not([type="submit"])')).click();
expect(firstInput.getAttribute('value')).toEqual('Carson');
expect(lastInput.getAttribute('value')).toEqual('Drew');
});
});
});
| {
"end_byte": 1459,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleFormGroup/e2e_test/simple_form_group_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/selectControl/module.ts_0_604 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {SelectControlComp} from './select_control_example';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [SelectControlComp],
bootstrap: [SelectControlComp],
})
export class AppModule {}
export {SelectControlComp as AppComponent};
| {
"end_byte": 604,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/selectControl/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/selectControl/select_control_example.ts_0_990 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion Component
import {Component} from '@angular/core';
@Component({
selector: 'example-app',
template: `
<form #f="ngForm">
<select name="state" ngModel>
<option value="" disabled>Choose a state</option>
<option *ngFor="let state of states" [ngValue]="state">
{{ state.abbrev }}
</option>
</select>
</form>
<p>Form value: {{ f.value | json }}</p>
<!-- example value: {state: {name: 'New York', abbrev: 'NY'} } -->
`,
standalone: false,
})
export class SelectControlComp {
states = [
{name: 'Arizona', abbrev: 'AZ'},
{name: 'California', abbrev: 'CA'},
{name: 'Colorado', abbrev: 'CO'},
{name: 'New York', abbrev: 'NY'},
{name: 'Pennsylvania', abbrev: 'PA'},
];
}
// #enddocregion
| {
"end_byte": 990,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/selectControl/select_control_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/selectControl/e2e_test/select_control_spec.ts_0_1100 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('selectControl example', () => {
afterEach(verifyNoBrowserErrors);
let select: ElementFinder;
let options: ElementArrayFinder;
let p: ElementFinder;
beforeEach(() => {
browser.get('/selectControl');
select = element(by.css('select'));
options = element.all(by.css('option'));
p = element(by.css('p'));
});
it('should initially select the placeholder option', () => {
expect(options.get(0).getAttribute('selected')).toBe('true');
});
it('should update the model when the value changes in the UI', () => {
select.click();
options.get(1).click();
expect(p.getText()).toEqual('Form value: { "state": { "name": "Arizona", "abbrev": "AZ" } }');
});
});
| {
"end_byte": 1100,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/selectControl/e2e_test/select_control_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/reactiveSelectControl/module.ts_0_633 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {ReactiveFormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {ReactiveSelectComp} from './reactive_select_control_example';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [ReactiveSelectComp],
bootstrap: [ReactiveSelectComp],
})
export class AppModule {}
export {ReactiveSelectComp as AppComponent};
| {
"end_byte": 633,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/reactiveSelectControl/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/reactiveSelectControl/reactive_select_control_example.ts_0_1062 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion Component
import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form">
<select formControlName="state">
<option *ngFor="let state of states" [ngValue]="state">
{{ state.abbrev }}
</option>
</select>
</form>
<p>Form value: {{ form.value | json }}</p>
<!-- {state: {name: 'New York', abbrev: 'NY'} } -->
`,
standalone: false,
})
export class ReactiveSelectComp {
states = [
{name: 'Arizona', abbrev: 'AZ'},
{name: 'California', abbrev: 'CA'},
{name: 'Colorado', abbrev: 'CO'},
{name: 'New York', abbrev: 'NY'},
{name: 'Pennsylvania', abbrev: 'PA'},
];
form = new FormGroup({
state: new FormControl(this.states[3]),
});
}
// #enddocregion
| {
"end_byte": 1062,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/reactiveSelectControl/reactive_select_control_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/reactiveSelectControl/e2e_test/reactive_select_control_spec.ts_0_1170 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('reactiveSelectControl example', () => {
afterEach(verifyNoBrowserErrors);
let select: ElementFinder;
let options: ElementArrayFinder;
let p: ElementFinder;
beforeEach(() => {
browser.get('/reactiveSelectControl');
select = element(by.css('select'));
options = element.all(by.css('option'));
p = element(by.css('p'));
});
it('should populate the initial selection', () => {
expect(select.getAttribute('value')).toEqual('3: Object');
expect(options.get(3).getAttribute('selected')).toBe('true');
});
it('should update the model when the value changes in the UI', () => {
select.click();
options.get(0).click();
expect(p.getText()).toEqual('Form value: { "state": { "name": "Arizona", "abbrev": "AZ" } }');
});
});
| {
"end_byte": 1170,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/reactiveSelectControl/e2e_test/reactive_select_control_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/radioButtons/module.ts_0_594 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {RadioButtonComp} from './radio_button_example';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [RadioButtonComp],
bootstrap: [RadioButtonComp],
})
export class AppModule {}
export {RadioButtonComp as AppComponent};
| {
"end_byte": 594,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/radioButtons/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/radioButtons/radio_button_example.ts_0_805 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
@Component({
selector: 'example-app',
template: `
<form #f="ngForm">
<input type="radio" value="beef" name="food" [(ngModel)]="myFood" />
Beef
<input type="radio" value="lamb" name="food" [(ngModel)]="myFood" />
Lamb
<input type="radio" value="fish" name="food" [(ngModel)]="myFood" />
Fish
</form>
<p>Form value: {{ f.value | json }}</p>
<!-- {food: 'lamb' } -->
<p>myFood value: {{ myFood }}</p>
<!-- 'lamb' -->
`,
standalone: false,
})
export class RadioButtonComp {
myFood = 'lamb';
}
| {
"end_byte": 805,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/radioButtons/radio_button_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/radioButtons/e2e_test/radio_button_spec.ts_0_1550 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementArrayFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('radioButtons example', () => {
afterEach(verifyNoBrowserErrors);
let inputs: ElementArrayFinder;
let paragraphs: ElementArrayFinder;
beforeEach(() => {
browser.get('/radioButtons');
inputs = element.all(by.css('input'));
paragraphs = element.all(by.css('p'));
});
it('should populate the UI with initial values', () => {
expect(inputs.get(0).getAttribute('checked')).toEqual(null);
expect(inputs.get(1).getAttribute('checked')).toEqual('true');
expect(inputs.get(2).getAttribute('checked')).toEqual(null);
expect(paragraphs.get(0).getText()).toEqual('Form value: { "food": "lamb" }');
expect(paragraphs.get(1).getText()).toEqual('myFood value: lamb');
});
it('update model and other buttons as the UI value changes', () => {
inputs.get(0).click();
expect(inputs.get(0).getAttribute('checked')).toEqual('true');
expect(inputs.get(1).getAttribute('checked')).toEqual(null);
expect(inputs.get(2).getAttribute('checked')).toEqual(null);
expect(paragraphs.get(0).getText()).toEqual('Form value: { "food": "beef" }');
expect(paragraphs.get(1).getText()).toEqual('myFood value: beef');
});
});
| {
"end_byte": 1550,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/radioButtons/e2e_test/radio_button_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleNgModel/module.ts_0_605 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {SimpleNgModelComp} from './simple_ng_model_example';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [SimpleNgModelComp],
bootstrap: [SimpleNgModelComp],
})
export class AppModule {}
export {SimpleNgModelComp as AppComponent};
| {
"end_byte": 605,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleNgModel/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleNgModel/simple_ng_model_example.ts_0_647 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion Component
import {Component} from '@angular/core';
@Component({
selector: 'example-app',
template: `
<input [(ngModel)]="name" #ctrl="ngModel" required />
<p>Value: {{ name }}</p>
<p>Valid: {{ ctrl.valid }}</p>
<button (click)="setValue()">Set value</button>
`,
standalone: false,
})
export class SimpleNgModelComp {
name: string = '';
setValue() {
this.name = 'Nancy';
}
}
// #enddocregion
| {
"end_byte": 647,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleNgModel/simple_ng_model_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleNgModel/e2e_test/simple_ng_model_spec.ts_0_1316 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('simpleNgModel example', () => {
afterEach(verifyNoBrowserErrors);
let input: ElementFinder;
let paragraphs: ElementArrayFinder;
let button: ElementFinder;
beforeEach(() => {
browser.get('/simpleNgModel');
input = element(by.css('input'));
paragraphs = element.all(by.css('p'));
button = element(by.css('button'));
});
it('should update the domain model as you type', () => {
input.click();
input.sendKeys('Carson');
expect(paragraphs.get(0).getText()).toEqual('Value: Carson');
});
it('should report the validity correctly', () => {
expect(paragraphs.get(1).getText()).toEqual('Valid: false');
input.click();
input.sendKeys('a');
expect(paragraphs.get(1).getText()).toEqual('Valid: true');
});
it('should set the value by changing the domain model', () => {
button.click();
expect(input.getAttribute('value')).toEqual('Nancy');
});
});
| {
"end_byte": 1316,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleNgModel/e2e_test/simple_ng_model_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleForm/module.ts_0_589 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {SimpleFormComp} from './simple_form_example';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [SimpleFormComp],
bootstrap: [SimpleFormComp],
})
export class AppModule {}
export {SimpleFormComp as AppComponent};
| {
"end_byte": 589,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleForm/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleForm/simple_form_example.ts_0_966 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* tslint:disable:no-console */
// #docregion Component
import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<input name="first" ngModel required #first="ngModel" />
<input name="last" ngModel />
<button>Submit</button>
</form>
<p>First name value: {{ first.value }}</p>
<p>First name valid: {{ first.valid }}</p>
<p>Form value: {{ f.value | json }}</p>
<p>Form valid: {{ f.valid }}</p>
`,
standalone: false,
})
export class SimpleFormComp {
onSubmit(f: NgForm) {
console.log(f.value); // { first: '', last: '' }
console.log(f.valid); // false
}
}
// #enddocregion
| {
"end_byte": 966,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleForm/simple_form_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/simpleForm/e2e_test/simple_form_spec.ts_0_1453 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementArrayFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('simpleForm example', () => {
afterEach(verifyNoBrowserErrors);
let inputs: ElementArrayFinder;
let paragraphs: ElementArrayFinder;
beforeEach(() => {
browser.get('/simpleForm');
inputs = element.all(by.css('input'));
paragraphs = element.all(by.css('p'));
});
it('should update the domain model as you type', () => {
inputs.get(0).click();
inputs.get(0).sendKeys('Nancy');
inputs.get(1).click();
inputs.get(1).sendKeys('Drew');
expect(paragraphs.get(0).getText()).toEqual('First name value: Nancy');
expect(paragraphs.get(2).getText()).toEqual('Form value: { "first": "Nancy", "last": "Drew" }');
});
it('should report the validity correctly', () => {
expect(paragraphs.get(1).getText()).toEqual('First name valid: false');
expect(paragraphs.get(3).getText()).toEqual('Form valid: false');
inputs.get(0).click();
inputs.get(0).sendKeys('a');
expect(paragraphs.get(1).getText()).toEqual('First name valid: true');
expect(paragraphs.get(3).getText()).toEqual('Form valid: true');
});
});
| {
"end_byte": 1453,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleForm/e2e_test/simple_form_spec.ts"
} |
angular/adev/src/content/api-examples/forms/ts/nestedFormGroup/module.ts_0_631 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {ReactiveFormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {NestedFormGroupComp} from './nested_form_group_example';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [NestedFormGroupComp],
bootstrap: [NestedFormGroupComp],
})
export class AppModule {}
export {NestedFormGroupComp as AppComponent};
| {
"end_byte": 631,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/nestedFormGroup/module.ts"
} |
angular/adev/src/content/api-examples/forms/ts/nestedFormGroup/nested_form_group_example.ts_0_1647 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* tslint:disable:no-console */
// #docregion Component
import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<p *ngIf="name.invalid">Name is invalid.</p>
<div formGroupName="name">
<input formControlName="first" placeholder="First name" />
<input formControlName="last" placeholder="Last name" />
</div>
<input formControlName="email" placeholder="Email" />
<button type="submit">Submit</button>
</form>
<button (click)="setPreset()">Set preset</button>
`,
standalone: false,
})
export class NestedFormGroupComp {
form = new FormGroup({
name: new FormGroup({
first: new FormControl('Nancy', Validators.minLength(2)),
last: new FormControl('Drew', Validators.required),
}),
email: new FormControl(),
});
get first(): any {
return this.form.get('name.first');
}
get name(): any {
return this.form.get('name');
}
onSubmit() {
console.log(this.first.value); // 'Nancy'
console.log(this.name.value); // {first: 'Nancy', last: 'Drew'}
console.log(this.form.value); // {name: {first: 'Nancy', last: 'Drew'}, email: ''}
console.log(this.form.status); // VALID
}
setPreset() {
this.name.setValue({first: 'Bess', last: 'Marvin'});
}
}
// #enddocregion
| {
"end_byte": 1647,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/nestedFormGroup/nested_form_group_example.ts"
} |
angular/adev/src/content/api-examples/forms/ts/nestedFormGroup/e2e_test/nested_form_group_spec.ts_0_1409 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
describe('nestedFormGroup example', () => {
afterEach(verifyNoBrowserErrors);
let firstInput: ElementFinder;
let lastInput: ElementFinder;
let button: ElementFinder;
beforeEach(() => {
browser.get('/nestedFormGroup');
firstInput = element(by.css('[formControlName="first"]'));
lastInput = element(by.css('[formControlName="last"]'));
button = element(by.css('button:not([type="submit"])'));
});
it('should populate the UI with initial values', () => {
expect(firstInput.getAttribute('value')).toEqual('Nancy');
expect(lastInput.getAttribute('value')).toEqual('Drew');
});
it('should show the error when name is invalid', () => {
firstInput.click();
firstInput.clear();
firstInput.sendKeys('a');
expect(element(by.css('p')).getText()).toEqual('Name is invalid.');
});
it('should set the value programmatically', () => {
button.click();
expect(firstInput.getAttribute('value')).toEqual('Bess');
expect(lastInput.getAttribute('value')).toEqual('Marvin');
});
});
| {
"end_byte": 1409,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/nestedFormGroup/e2e_test/nested_form_group_spec.ts"
} |
angular/adev/src/content/api-examples/core/main.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import 'zone.js/lib/browser/rollup-main';
import 'zone.js/lib/zone-spec/task-tracking';
// okd
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {TestsAppModule} from './test_module';
platformBrowserDynamic().bootstrapModule(TestsAppModule);
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/main.ts"
} |
angular/adev/src/content/api-examples/core/start-server.js_0_552 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
const protractorUtils = require('@bazel/protractor/protractor-utils');
const protractor = require('protractor');
module.exports = async function (config) {
const {port} = await protractorUtils.runServer(config.workspace, config.server, '--port', []);
const serverUrl = `http://localhost:${port}`;
protractor.browser.baseUrl = serverUrl;
};
| {
"end_byte": 552,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/start-server.js"
} |
angular/adev/src/content/api-examples/core/test_module.ts_0_1866 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import * as animationDslExample from './animation/ts/dsl/module';
import * as diContentChildExample from './di/ts/contentChild/module';
import * as diContentChildrenExample from './di/ts/contentChildren/module';
import * as diViewChildExample from './di/ts/viewChild/module';
import * as diViewChildrenExample from './di/ts/viewChildren/module';
import * as testabilityWhenStableExample from './testability/ts/whenStable/module';
@Component({
selector: 'example-app',
template: '<router-outlet></router-outlet>',
standalone: false,
})
export class TestsAppComponent {}
@NgModule({
imports: [
animationDslExample.AppModule,
diContentChildExample.AppModule,
diContentChildrenExample.AppModule,
diViewChildExample.AppModule,
diViewChildrenExample.AppModule,
testabilityWhenStableExample.AppModule,
// Router configuration so that the individual e2e tests can load their
// app components.
RouterModule.forRoot([
{path: 'animation/dsl', component: animationDslExample.AppComponent},
{path: 'di/contentChild', component: diContentChildExample.AppComponent},
{path: 'di/contentChildren', component: diContentChildrenExample.AppComponent},
{path: 'di/viewChild', component: diViewChildExample.AppComponent},
{path: 'di/viewChildren', component: diViewChildrenExample.AppComponent},
{path: 'testability/whenStable', component: testabilityWhenStableExample.AppComponent},
]),
],
declarations: [TestsAppComponent],
bootstrap: [TestsAppComponent],
})
export class TestsAppModule {}
| {
"end_byte": 1866,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/test_module.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/metadata_spec.ts_0_5289 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
Directive,
Host,
Injectable,
Injector,
Optional,
Self,
SkipSelf,
} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
{
describe('di metadata examples', () => {
describe('Inject', () => {
it('works without decorator', () => {
// #docregion InjectWithoutDecorator
class Engine {}
@Injectable()
class Car {
constructor(public engine: Engine) {} // same as constructor(@Inject(Engine) engine:Engine)
}
const injector = Injector.create({
providers: [
{provide: Engine, deps: []},
{provide: Car, deps: [Engine]},
],
});
expect(injector.get(Car).engine instanceof Engine).toBe(true);
// #enddocregion
});
});
describe('Optional', () => {
it('works', () => {
// #docregion Optional
class Engine {}
@Injectable()
class Car {
constructor(@Optional() public engine: Engine) {}
}
const injector = Injector.create({
providers: [{provide: Car, deps: [[new Optional(), Engine]]}],
});
expect(injector.get(Car).engine).toBeNull();
// #enddocregion
});
});
describe('Injectable', () => {
it('works', () => {
// #docregion Injectable
@Injectable()
class UsefulService {}
@Injectable()
class NeedsService {
constructor(public service: UsefulService) {}
}
const injector = Injector.create({
providers: [
{provide: NeedsService, deps: [UsefulService]},
{provide: UsefulService, deps: []},
],
});
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
// #enddocregion
});
});
describe('Self', () => {
it('works', () => {
// #docregion Self
class Dependency {}
@Injectable()
class NeedsDependency {
constructor(@Self() public dependency: Dependency) {}
}
let inj = Injector.create({
providers: [
{provide: Dependency, deps: []},
{provide: NeedsDependency, deps: [[new Self(), Dependency]]},
],
});
const nd = inj.get(NeedsDependency);
expect(nd.dependency instanceof Dependency).toBe(true);
const child = Injector.create({
providers: [{provide: NeedsDependency, deps: [[new Self(), Dependency]]}],
parent: inj,
});
expect(() => child.get(NeedsDependency)).toThrowError();
// #enddocregion
});
});
describe('SkipSelf', () => {
it('works', () => {
// #docregion SkipSelf
class Dependency {}
@Injectable()
class NeedsDependency {
constructor(@SkipSelf() public dependency: Dependency) {}
}
const parent = Injector.create({providers: [{provide: Dependency, deps: []}]});
const child = Injector.create({
providers: [{provide: NeedsDependency, deps: [Dependency]}],
parent,
});
expect(child.get(NeedsDependency).dependency instanceof Dependency).toBe(true);
const inj = Injector.create({
providers: [{provide: NeedsDependency, deps: [[new Self(), Dependency]]}],
});
expect(() => inj.get(NeedsDependency)).toThrowError();
// #enddocregion
});
});
describe('Host', () => {
it('works', () => {
// #docregion Host
class OtherService {}
class HostService {}
@Directive({
selector: 'child-directive',
standalone: false,
})
class ChildDirective {
logs: string[] = [];
constructor(@Optional() @Host() os: OtherService, @Optional() @Host() hs: HostService) {
// os is null: true
this.logs.push(`os is null: ${os === null}`);
// hs is an instance of HostService: true
this.logs.push(`hs is an instance of HostService: ${hs instanceof HostService}`);
}
}
@Component({
selector: 'parent-cmp',
viewProviders: [HostService],
template: '<child-directive></child-directive>',
standalone: false,
})
class ParentCmp {}
@Component({
selector: 'app',
viewProviders: [OtherService],
template: '<parent-cmp></parent-cmp>',
standalone: false,
})
class App {}
// #enddocregion
TestBed.configureTestingModule({
declarations: [App, ParentCmp, ChildDirective],
});
let cmp: ComponentFixture<App> = undefined!;
expect(() => (cmp = TestBed.createComponent(App))).not.toThrow();
expect(cmp.debugElement.children[0].children[0].injector.get(ChildDirective).logs).toEqual([
'os is null: true',
'hs is an instance of HostService: true',
]);
});
});
});
}
| {
"end_byte": 5289,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/metadata_spec.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/injector_spec.ts_0_3039 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
inject,
InjectFlags,
InjectionToken,
InjectOptions,
Injector,
ProviderToken,
ɵsetCurrentInjector as setCurrentInjector,
ɵsetInjectorProfilerContext,
} from '@angular/core';
class MockRootScopeInjector implements Injector {
constructor(readonly parent: Injector) {}
get<T>(
token: ProviderToken<T>,
defaultValue?: any,
flags: InjectFlags | InjectOptions = InjectFlags.Default,
): T {
if ((token as any).ɵprov && (token as any).ɵprov.providedIn === 'root') {
const old = setCurrentInjector(this);
const previousInjectorProfilerContext = ɵsetInjectorProfilerContext({
injector: this,
token: null,
});
try {
return (token as any).ɵprov.factory();
} finally {
setCurrentInjector(old);
ɵsetInjectorProfilerContext(previousInjectorProfilerContext);
}
}
return this.parent.get(token, defaultValue, flags);
}
}
{
describe('injector metadata examples', () => {
it('works', () => {
// #docregion Injector
const injector: Injector = Injector.create({
providers: [{provide: 'validToken', useValue: 'Value'}],
});
expect(injector.get('validToken')).toEqual('Value');
expect(() => injector.get('invalidToken')).toThrowError();
expect(injector.get('invalidToken', 'notFound')).toEqual('notFound');
// #enddocregion
});
it('injects injector', () => {
// #docregion injectInjector
const injector = Injector.create({providers: []});
expect(injector.get(Injector)).toBe(injector);
// #enddocregion
});
it('should infer type', () => {
// #docregion InjectionToken
const BASE_URL = new InjectionToken<string>('BaseUrl');
const injector = Injector.create({
providers: [{provide: BASE_URL, useValue: 'http://localhost'}],
});
const url = injector.get(BASE_URL);
// Note: since `BASE_URL` is `InjectionToken<string>`
// `url` is correctly inferred to be `string`
expect(url).toBe('http://localhost');
// #enddocregion
});
it('injects a tree-shakeable InjectionToken', () => {
class MyDep {}
const injector = new MockRootScopeInjector(
Injector.create({providers: [{provide: MyDep, deps: []}]}),
);
// #docregion ShakableInjectionToken
class MyService {
constructor(readonly myDep: MyDep) {}
}
const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', {
providedIn: 'root',
factory: () => new MyService(inject(MyDep)),
});
const instance = injector.get(MY_SERVICE_TOKEN);
expect(instance instanceof MyService).toBeTruthy();
expect(instance.myDep instanceof MyDep).toBeTruthy();
// #enddocregion
});
});
}
| {
"end_byte": 3039,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/injector_spec.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/provider_spec.ts_0_6666 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable, InjectionToken, Injector, Optional} from '@angular/core';
{
describe('Provider examples', () => {
describe('TypeProvider', () => {
it('works', () => {
// #docregion TypeProvider
@Injectable()
class Greeting {
salutation = 'Hello';
}
const injector = Injector.create({providers: [{provide: Greeting, useClass: Greeting}]});
expect(injector.get(Greeting).salutation).toBe('Hello');
// #enddocregion
});
});
describe('ValueProvider', () => {
it('works', () => {
// #docregion ValueProvider
const injector = Injector.create({providers: [{provide: String, useValue: 'Hello'}]});
expect(injector.get(String)).toEqual('Hello');
// #enddocregion
});
});
describe('MultiProviderAspect', () => {
it('works', () => {
// #docregion MultiProviderAspect
const locale = new InjectionToken<string[]>('locale');
const injector = Injector.create({
providers: [
{provide: locale, multi: true, useValue: 'en'},
{provide: locale, multi: true, useValue: 'sk'},
],
});
const locales: string[] = injector.get(locale);
expect(locales).toEqual(['en', 'sk']);
// #enddocregion
});
});
describe('ClassProvider', () => {
it('works', () => {
// #docregion ClassProvider
abstract class Shape {
name!: string;
}
class Square extends Shape {
override name = 'square';
}
const injector = Injector.create({providers: [{provide: Shape, useValue: new Square()}]});
const shape: Shape = injector.get(Shape);
expect(shape.name).toEqual('square');
expect(shape instanceof Square).toBe(true);
// #enddocregion
});
it('is different then useExisting', () => {
// #docregion ClassProviderDifference
class Greeting {
salutation = 'Hello';
}
class FormalGreeting extends Greeting {
override salutation = 'Greetings';
}
const injector = Injector.create({
providers: [
{provide: FormalGreeting, useClass: FormalGreeting},
{provide: Greeting, useClass: FormalGreeting},
],
});
// The injector returns different instances.
// See: {provide: ?, useExisting: ?} if you want the same instance.
expect(injector.get(FormalGreeting)).not.toBe(injector.get(Greeting));
// #enddocregion
});
});
describe('StaticClassProvider', () => {
it('works', () => {
// #docregion StaticClassProvider
abstract class Shape {
name!: string;
}
class Square extends Shape {
override name = 'square';
}
const injector = Injector.create({
providers: [{provide: Shape, useClass: Square, deps: []}],
});
const shape: Shape = injector.get(Shape);
expect(shape.name).toEqual('square');
expect(shape instanceof Square).toBe(true);
// #enddocregion
});
it('is different then useExisting', () => {
// #docregion StaticClassProviderDifference
class Greeting {
salutation = 'Hello';
}
class FormalGreeting extends Greeting {
override salutation = 'Greetings';
}
const injector = Injector.create({
providers: [
{provide: FormalGreeting, useClass: FormalGreeting, deps: []},
{provide: Greeting, useClass: FormalGreeting, deps: []},
],
});
// The injector returns different instances.
// See: {provide: ?, useExisting: ?} if you want the same instance.
expect(injector.get(FormalGreeting)).not.toBe(injector.get(Greeting));
// #enddocregion
});
});
describe('ConstructorProvider', () => {
it('works', () => {
// #docregion ConstructorProvider
class Square {
name = 'square';
}
const injector = Injector.create({providers: [{provide: Square, deps: []}]});
const shape: Square = injector.get(Square);
expect(shape.name).toEqual('square');
expect(shape instanceof Square).toBe(true);
// #enddocregion
});
});
describe('ExistingProvider', () => {
it('works', () => {
// #docregion ExistingProvider
class Greeting {
salutation = 'Hello';
}
class FormalGreeting extends Greeting {
override salutation = 'Greetings';
}
const injector = Injector.create({
providers: [
{provide: FormalGreeting, deps: []},
{provide: Greeting, useExisting: FormalGreeting},
],
});
expect(injector.get(Greeting).salutation).toEqual('Greetings');
expect(injector.get(FormalGreeting).salutation).toEqual('Greetings');
expect(injector.get(FormalGreeting)).toBe(injector.get(Greeting));
// #enddocregion
});
});
describe('FactoryProvider', () => {
it('works', () => {
// #docregion FactoryProvider
const Location = new InjectionToken('location');
const Hash = new InjectionToken('hash');
const injector = Injector.create({
providers: [
{provide: Location, useValue: 'https://angular.io/#someLocation'},
{
provide: Hash,
useFactory: (location: string) => location.split('#')[1],
deps: [Location],
},
],
});
expect(injector.get(Hash)).toEqual('someLocation');
// #enddocregion
});
it('supports optional dependencies', () => {
// #docregion FactoryProviderOptionalDeps
const Location = new InjectionToken('location');
const Hash = new InjectionToken('hash');
const injector = Injector.create({
providers: [
{
provide: Hash,
useFactory: (location: string) => `Hash for: ${location}`,
// use a nested array to define metadata for dependencies.
deps: [[new Optional(), Location]],
},
],
});
expect(injector.get(Hash)).toEqual('Hash for: null');
// #enddocregion
});
});
});
}
| {
"end_byte": 6666,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/provider_spec.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/forward_ref/forward_ref_spec.ts_0_1621 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {forwardRef, Inject, Injectable, Injector, resolveForwardRef} from '@angular/core';
{
describe('forwardRef examples', () => {
it('ForwardRefFn example works', () => {
// #docregion forward_ref_fn
const ref = forwardRef(() => Lock);
// #enddocregion
expect(ref).not.toBeNull();
class Lock {}
});
it('can be used to inject a class defined later', () => {
// #docregion forward_ref
@Injectable()
class Door {
lock: Lock;
// Door attempts to inject Lock, despite it not being defined yet.
// forwardRef makes this possible.
constructor(@Inject(forwardRef(() => Lock)) lock: Lock) {
this.lock = lock;
}
}
// Only at this point Lock is defined.
class Lock {}
const injector = Injector.create({
providers: [
{provide: Lock, deps: []},
{provide: Door, deps: [Lock]},
],
});
expect(injector.get(Door) instanceof Door).toBe(true);
expect(injector.get(Door).lock instanceof Lock).toBe(true);
// #enddocregion
});
it('can be unwrapped', () => {
// #docregion resolve_forward_ref
const ref = forwardRef(() => 'refValue');
expect(resolveForwardRef(ref as any)).toEqual('refValue');
expect(resolveForwardRef('regularValue')).toEqual('regularValue');
// #enddocregion
});
});
}
| {
"end_byte": 1621,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/forward_ref/forward_ref_spec.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/contentChild/content_child_howto.ts_0_634 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion HowTo
import {AfterContentInit, ContentChild, Directive} from '@angular/core';
@Directive({
selector: 'child-directive',
standalone: false,
})
class ChildDirective {}
@Directive({
selector: 'someDir',
standalone: false,
})
class SomeDir implements AfterContentInit {
@ContentChild(ChildDirective) contentChild!: ChildDirective;
ngAfterContentInit() {
// contentChild is set
}
}
// #enddocregion
| {
"end_byte": 634,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/contentChild/content_child_howto.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/contentChild/module.ts_0_564 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ContentChildComp, Pane, Tab} from './content_child_example';
@NgModule({
imports: [BrowserModule],
declarations: [ContentChildComp, Pane, Tab],
bootstrap: [ContentChildComp],
})
export class AppModule {}
export {ContentChildComp as AppComponent};
| {
"end_byte": 564,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/contentChild/module.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/contentChild/content_child_example.ts_0_949 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion Component
import {Component, ContentChild, Directive, Input} from '@angular/core';
@Directive({
selector: 'pane',
standalone: false,
})
export class Pane {
@Input() id!: string;
}
@Component({
selector: 'tab',
template: `
<div>pane: {{ pane?.id }}</div>
`,
standalone: false,
})
export class Tab {
@ContentChild(Pane) pane!: Pane;
}
@Component({
selector: 'example-app',
template: `
<tab>
<pane id="1" *ngIf="shouldShow"></pane>
<pane id="2" *ngIf="!shouldShow"></pane>
</tab>
<button (click)="toggle()">Toggle</button>
`,
standalone: false,
})
export class ContentChildComp {
shouldShow = true;
toggle() {
this.shouldShow = !this.shouldShow;
}
}
// #enddocregion
| {
"end_byte": 949,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/contentChild/content_child_example.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/contentChild/e2e_test/content_child_spec.ts_0_822 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index';
describe('contentChild example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/di/contentChild');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query content child', () => {
expect(result.getText()).toEqual('pane: 1');
button.click();
expect(result.getText()).toEqual('pane: 2');
});
});
| {
"end_byte": 822,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/contentChild/e2e_test/content_child_spec.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/viewChild/module.ts_0_540 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Pane, ViewChildComp} from './view_child_example';
@NgModule({
imports: [BrowserModule],
declarations: [ViewChildComp, Pane],
bootstrap: [ViewChildComp],
})
export class AppModule {}
export {ViewChildComp as AppComponent};
| {
"end_byte": 540,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/viewChild/module.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/viewChild/view_child_example.ts_0_934 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion Component
import {Component, Directive, Input, ViewChild} from '@angular/core';
@Directive({
selector: 'pane',
standalone: false,
})
export class Pane {
@Input() id!: string;
}
@Component({
selector: 'example-app',
template: `
<pane id="1" *ngIf="shouldShow"></pane>
<pane id="2" *ngIf="!shouldShow"></pane>
<button (click)="toggle()">Toggle</button>
<div>Selected: {{ selectedPane }}</div>
`,
standalone: false,
})
export class ViewChildComp {
@ViewChild(Pane)
set pane(v: Pane) {
setTimeout(() => {
this.selectedPane = v.id;
}, 0);
}
selectedPane: string = '';
shouldShow = true;
toggle() {
this.shouldShow = !this.shouldShow;
}
}
// #enddocregion
| {
"end_byte": 934,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/viewChild/view_child_example.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/viewChild/view_child_howto.ts_0_647 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion HowTo
import {AfterViewInit, Component, Directive, ViewChild} from '@angular/core';
@Directive({
selector: 'child-directive',
standalone: false,
})
class ChildDirective {}
@Component({
selector: 'someCmp',
templateUrl: 'someCmp.html',
standalone: false,
})
class SomeCmp implements AfterViewInit {
@ViewChild(ChildDirective) child!: ChildDirective;
ngAfterViewInit() {
// child is set
}
}
// #enddocregion
| {
"end_byte": 647,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/viewChild/view_child_howto.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/viewChild/e2e_test/view_child_spec.ts_0_821 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index';
describe('viewChild example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/di/viewChild');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query view child', () => {
expect(result.getText()).toEqual('Selected: 1');
button.click();
expect(result.getText()).toEqual('Selected: 2');
});
});
| {
"end_byte": 821,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/viewChild/e2e_test/view_child_spec.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/contentChildren/module.ts_0_579 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ContentChildrenComp, Pane, Tab} from './content_children_example';
@NgModule({
imports: [BrowserModule],
declarations: [ContentChildrenComp, Pane, Tab],
bootstrap: [ContentChildrenComp],
})
export class AppModule {}
export {ContentChildrenComp as AppComponent};
| {
"end_byte": 579,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/contentChildren/module.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/contentChildren/content_children_example.ts_0_1554 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion Component
import {Component, ContentChildren, Directive, Input, QueryList} from '@angular/core';
@Directive({
selector: 'pane',
standalone: false,
})
export class Pane {
@Input() id!: string;
}
@Component({
selector: 'tab',
template: `
<div class="top-level">Top level panes: {{ serializedPanes }}</div>
<div class="nested">Arbitrary nested panes: {{ serializedNestedPanes }}</div>
`,
standalone: false,
})
export class Tab {
@ContentChildren(Pane) topLevelPanes!: QueryList<Pane>;
@ContentChildren(Pane, {descendants: true}) arbitraryNestedPanes!: QueryList<Pane>;
get serializedPanes(): string {
return this.topLevelPanes ? this.topLevelPanes.map((p) => p.id).join(', ') : '';
}
get serializedNestedPanes(): string {
return this.arbitraryNestedPanes ? this.arbitraryNestedPanes.map((p) => p.id).join(', ') : '';
}
}
@Component({
selector: 'example-app',
template: `
<tab>
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow">
<tab>
<pane id="3_1"></pane>
<pane id="3_2"></pane>
</tab>
</pane>
</tab>
<button (click)="show()">Show 3</button>
`,
standalone: false,
})
export class ContentChildrenComp {
shouldShow = false;
show() {
this.shouldShow = true;
}
}
// #enddocregion
| {
"end_byte": 1554,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/contentChildren/content_children_example.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/contentChildren/content_children_howto.ts_0_668 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion HowTo
import {AfterContentInit, ContentChildren, Directive, QueryList} from '@angular/core';
@Directive({
selector: 'child-directive',
standalone: false,
})
class ChildDirective {}
@Directive({
selector: 'someDir',
standalone: false,
})
class SomeDir implements AfterContentInit {
@ContentChildren(ChildDirective) contentChildren!: QueryList<ChildDirective>;
ngAfterContentInit() {
// contentChildren is set
}
}
// #enddocregion
| {
"end_byte": 668,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/contentChildren/content_children_howto.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/contentChildren/e2e_test/content_children_spec.ts_0_1230 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index';
describe('contentChildren example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let resultTopLevel: ElementFinder;
let resultNested: ElementFinder;
beforeEach(() => {
browser.get('/di/contentChildren');
button = element(by.css('button'));
resultTopLevel = element(by.css('.top-level'));
resultNested = element(by.css('.nested'));
});
it('should query content children', () => {
expect(resultTopLevel.getText()).toEqual('Top level panes: 1, 2');
button.click();
expect(resultTopLevel.getText()).toEqual('Top level panes: 1, 2, 3');
});
it('should query nested content children', () => {
expect(resultNested.getText()).toEqual('Arbitrary nested panes: 1, 2');
button.click();
expect(resultNested.getText()).toEqual('Arbitrary nested panes: 1, 2, 3, 3_1, 3_2');
});
});
| {
"end_byte": 1230,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/contentChildren/e2e_test/content_children_spec.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/viewChildren/view_children_howto.ts_0_689 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion HowTo
import {AfterViewInit, Component, Directive, QueryList, ViewChildren} from '@angular/core';
@Directive({
selector: 'child-directive',
standalone: false,
})
class ChildDirective {}
@Component({
selector: 'someCmp',
templateUrl: 'someCmp.html',
standalone: false,
})
class SomeCmp implements AfterViewInit {
@ViewChildren(ChildDirective) viewChildren!: QueryList<ChildDirective>;
ngAfterViewInit() {
// viewChildren is set
}
}
// #enddocregion
| {
"end_byte": 689,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/viewChildren/view_children_howto.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/viewChildren/module.ts_0_555 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Pane, ViewChildrenComp} from './view_children_example';
@NgModule({
imports: [BrowserModule],
declarations: [ViewChildrenComp, Pane],
bootstrap: [ViewChildrenComp],
})
export class AppModule {}
export {ViewChildrenComp as AppComponent};
| {
"end_byte": 555,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/viewChildren/module.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/viewChildren/view_children_example.ts_0_1214 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion Component
import {AfterViewInit, Component, Directive, Input, QueryList, ViewChildren} from '@angular/core';
@Directive({
selector: 'pane',
standalone: false,
})
export class Pane {
@Input() id!: string;
}
@Component({
selector: 'example-app',
template: `
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow"></pane>
<button (click)="show()">Show 3</button>
<div>panes: {{ serializedPanes }}</div>
`,
standalone: false,
})
export class ViewChildrenComp implements AfterViewInit {
@ViewChildren(Pane) panes!: QueryList<Pane>;
serializedPanes: string = '';
shouldShow = false;
show() {
this.shouldShow = true;
}
ngAfterViewInit() {
this.calculateSerializedPanes();
this.panes.changes.subscribe((r) => {
this.calculateSerializedPanes();
});
}
calculateSerializedPanes() {
setTimeout(() => {
this.serializedPanes = this.panes.map((p) => p.id).join(', ');
}, 0);
}
}
// #enddocregion
| {
"end_byte": 1214,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/viewChildren/view_children_example.ts"
} |
angular/adev/src/content/api-examples/core/di/ts/viewChildren/e2e_test/view_children_spec.ts_0_833 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element, ElementFinder} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index';
describe('viewChildren example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/di/viewChildren');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query view children', () => {
expect(result.getText()).toEqual('panes: 1, 2');
button.click();
expect(result.getText()).toEqual('panes: 1, 2, 3');
});
});
| {
"end_byte": 833,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/di/ts/viewChildren/e2e_test/view_children_spec.ts"
} |
angular/adev/src/content/api-examples/core/testability/ts/whenStable/testability_example.ts_0_815 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
@Component({
selector: 'example-app',
template: `
<button class="start-button" (click)="start()">Start long-running task</button>
<div class="status">Status: {{ status }}</div>
`,
standalone: false,
})
export class StableTestCmp {
status = 'none';
start() {
this.status = 'running';
setTimeout(() => {
this.status = 'done';
}, 5000);
}
}
@NgModule({imports: [BrowserModule], declarations: [StableTestCmp], bootstrap: [StableTestCmp]})
export class AppModule {}
| {
"end_byte": 815,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/testability/ts/whenStable/testability_example.ts"
} |
angular/adev/src/content/api-examples/core/testability/ts/whenStable/module.ts_0_283 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {AppModule, StableTestCmp as AppComponent} from './testability_example';
| {
"end_byte": 283,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/testability/ts/whenStable/module.ts"
} |
angular/adev/src/content/api-examples/core/testability/ts/whenStable/e2e_test/testability_example_spec.ts_0_1561 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {browser, by, element} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index';
// Declare the global "window" and "document" constant since we don't want to add the "dom"
// TypeScript lib for the e2e specs that execute code in the browser and reference such
// global constants.
declare const window: any;
declare const document: any;
describe('testability example', () => {
afterEach(verifyNoBrowserErrors);
describe('using task tracking', () => {
const URL = '/testability/whenStable/';
it('times out with a list of tasks', (done) => {
browser.get(URL);
browser.ignoreSynchronization = true;
// Script that runs in the browser and calls whenStable with a timeout.
let waitWithResultScript = function (done: any) {
let rootEl = document.querySelector('example-app');
let testability = window.getAngularTestability(rootEl);
testability.whenStable(() => {
done();
}, 1000);
};
element(by.css('.start-button')).click();
browser.driver.executeAsyncScript(waitWithResultScript).then(() => {
expect(element(by.css('.status')).getText()).not.toContain('done');
done();
});
});
afterAll(() => {
browser.ignoreSynchronization = false;
});
});
});
| {
"end_byte": 1561,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/testability/ts/whenStable/e2e_test/testability_example_spec.ts"
} |
angular/adev/src/content/api-examples/core/animation/ts/dsl/module.ts_0_281 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {AppModule, MyExpandoCmp as AppComponent} from './animation_example';
| {
"end_byte": 281,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/animation/ts/dsl/module.ts"
} |
angular/adev/src/content/api-examples/core/animation/ts/dsl/animation_example.ts_0_1712 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {animate, state, style, transition, trigger} from '@angular/animations';
import {Component, NgModule} from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@Component({
selector: 'example-app',
styles: [
`
.toggle-container {
background-color: white;
border: 10px solid black;
width: 200px;
text-align: center;
line-height: 100px;
font-size: 50px;
box-sizing: border-box;
overflow: hidden;
}
`,
],
animations: [
trigger('openClose', [
state('collapsed, void', style({height: '0px', color: 'maroon', borderColor: 'maroon'})),
state('expanded', style({height: '*', borderColor: 'green', color: 'green'})),
transition('collapsed <=> expanded', [animate(500, style({height: '250px'})), animate(500)]),
]),
],
template: `
<button (click)="expand()">Open</button>
<button (click)="collapse()">Closed</button>
<hr />
<div class="toggle-container" [@openClose]="stateExpression">Look at this box</div>
`,
standalone: false,
})
export class MyExpandoCmp {
// TODO(issue/24571): remove '!'.
stateExpression!: string;
constructor() {
this.collapse();
}
expand() {
this.stateExpression = 'expanded';
}
collapse() {
this.stateExpression = 'collapsed';
}
}
@NgModule({
imports: [BrowserAnimationsModule],
declarations: [MyExpandoCmp],
bootstrap: [MyExpandoCmp],
})
export class AppModule {}
| {
"end_byte": 1712,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/animation/ts/dsl/animation_example.ts"
} |
angular/adev/src/content/api-examples/core/animation/ts/dsl/e2e_test/animation_example_spec.ts_0_973 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {$, browser, by, element, ExpectedConditions} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index';
function waitForElement(selector: string) {
const EC = ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('animation example', () => {
afterEach(verifyNoBrowserErrors);
describe('index view', () => {
const URL = '/animation/dsl/';
it('should list out the current collection of items', () => {
browser.get(URL);
waitForElement('.toggle-container');
expect(element.all(by.css('.toggle-container')).get(0).getText()).toEqual('Look at this box');
});
});
});
| {
"end_byte": 973,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/animation/ts/dsl/e2e_test/animation_example_spec.ts"
} |
angular/adev/src/content/api-examples/core/testing/ts/fake_async.ts_0_1062 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {discardPeriodicTasks, fakeAsync, tick} from '@angular/core/testing';
// #docregion basic
describe('this test', () => {
it(
'looks async but is synchronous',
<any>fakeAsync((): void => {
let flag = false;
setTimeout(() => {
flag = true;
}, 100);
expect(flag).toBe(false);
tick(50);
expect(flag).toBe(false);
tick(50);
expect(flag).toBe(true);
}),
);
});
// #enddocregion
describe('this test', () => {
it(
'aborts a periodic timer',
<any>fakeAsync((): void => {
// This timer is scheduled but doesn't need to complete for the
// test to pass (maybe it's a timeout for some operation).
// Leaving it will cause the test to fail...
setInterval(() => {}, 100);
// Unless we clean it up first.
discardPeriodicTasks();
}),
);
});
| {
"end_byte": 1062,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/testing/ts/fake_async.ts"
} |
angular/adev/src/content/api-examples/core/testing/ts/example_spec.ts_0_520 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Import the "fake_async" example that registers tests which are shown as examples. These need
// to be valid tests, so we run them here. Note that we need to add this layer of abstraction here
// because the "jasmine_node_test" rule only picks up test files with the "_spec.ts" file suffix.
import './fake_async';
| {
"end_byte": 520,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/testing/ts/example_spec.ts"
} |
angular/adev/src/content/api-examples/core/ts/prod_mode/my_component.ts_0_376 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
@Component({
selector: 'my-component',
template: '<h1>My Component</h1>',
standalone: false,
})
export class MyComponent {}
| {
"end_byte": 376,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/prod_mode/my_component.ts"
} |
angular/adev/src/content/api-examples/core/ts/prod_mode/prod_mode_example.ts_0_629 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {enableProdMode, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {MyComponent} from './my_component';
enableProdMode();
@NgModule({imports: [BrowserModule], declarations: [MyComponent], bootstrap: [MyComponent]})
export class AppModule {}
platformBrowserDynamic().bootstrapModule(AppModule);
| {
"end_byte": 629,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/prod_mode/prod_mode_example.ts"
} |
angular/adev/src/content/api-examples/core/ts/bootstrap/bootstrap.ts_0_684 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
@Component({
selector: 'app-root',
template: 'Hello {{ name }}!',
standalone: false,
})
class MyApp {
name: string = 'World';
}
@NgModule({imports: [BrowserModule], bootstrap: [MyApp]})
class AppModule {}
export function main() {
platformBrowserDynamic().bootstrapModule(AppModule);
}
| {
"end_byte": 684,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/bootstrap/bootstrap.ts"
} |
angular/adev/src/content/api-examples/core/ts/platform/platform.ts_0_2124 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ApplicationRef, Component, DoBootstrap, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
@Component({
selector: 'app-root',
template: `
<h1>Component One</h1>
`,
standalone: false,
})
export class ComponentOne {}
@Component({
selector: 'app-root',
template: `
<h1>Component Two</h1>
`,
standalone: false,
})
export class ComponentTwo {}
@Component({
selector: 'app-root',
template: `
<h1>Component Three</h1>
`,
standalone: false,
})
export class ComponentThree {}
@Component({
selector: 'app-root',
template: `
<h1>Component Four</h1>
`,
standalone: false,
})
export class ComponentFour {}
@NgModule({imports: [BrowserModule], declarations: [ComponentOne, ComponentTwo]})
export class AppModule implements DoBootstrap {
// #docregion componentSelector
ngDoBootstrap(appRef: ApplicationRef) {
this.fetchDataFromApi().then((componentName: string) => {
if (componentName === 'ComponentOne') {
appRef.bootstrap(ComponentOne);
} else {
appRef.bootstrap(ComponentTwo);
}
});
}
// #enddocregion
fetchDataFromApi(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve('ComponentTwo');
}, 2000);
});
}
}
@NgModule({imports: [BrowserModule], declarations: [ComponentThree]})
export class AppModuleTwo implements DoBootstrap {
// #docregion cssSelector
ngDoBootstrap(appRef: ApplicationRef) {
appRef.bootstrap(ComponentThree, '#root-element');
}
// #enddocregion cssSelector
}
@NgModule({imports: [BrowserModule], declarations: [ComponentFour]})
export class AppModuleThree implements DoBootstrap {
// #docregion domNode
ngDoBootstrap(appRef: ApplicationRef) {
const element = document.querySelector('#root-element');
appRef.bootstrap(ComponentFour, element);
}
// #enddocregion domNode
}
| {
"end_byte": 2124,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/platform/platform.ts"
} |
angular/adev/src/content/api-examples/core/ts/pipes/pipeTransFormEx_module.ts_0_449 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {TruncatePipe as SimpleTruncatePipe} from './simple_truncate';
import {TruncatePipe} from './truncate';
@NgModule({declarations: [SimpleTruncatePipe, TruncatePipe]})
export class TruncateModule {}
| {
"end_byte": 449,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/pipes/pipeTransFormEx_module.ts"
} |
angular/adev/src/content/api-examples/core/ts/pipes/truncate.ts_0_506 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'truncate',
standalone: false,
})
export class TruncatePipe implements PipeTransform {
transform(value: string, length: number, symbol: string) {
return value.split(' ').slice(0, length).join(' ') + symbol;
}
}
| {
"end_byte": 506,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/pipes/truncate.ts"
} |
angular/adev/src/content/api-examples/core/ts/pipes/simple_truncate.ts_0_468 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'truncate',
standalone: false,
})
export class TruncatePipe implements PipeTransform {
transform(value: string) {
return value.split(' ').slice(0, 2).join(' ') + '...';
}
}
| {
"end_byte": 468,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/pipes/simple_truncate.ts"
} |
angular/adev/src/content/api-examples/core/ts/metadata/directives.ts_0_1958 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* tslint:disable:no-console */
import {Component, Directive, EventEmitter, NgModule} from '@angular/core';
// #docregion component-input
@Component({
selector: 'app-bank-account',
inputs: ['bankName', 'id: account-id'],
template: `
Bank Name: {{ bankName }} Account Id: {{ id }}
`,
standalone: false,
})
export class BankAccountComponent {
bankName: string | null = null;
id: string | null = null;
// this property is not bound, and won't be automatically updated by Angular
normalizedBankName: string | null = null;
}
@Component({
selector: 'app-my-input',
template: `
<app-bank-account bankName="RBC" account-id="4747"></app-bank-account>
`,
standalone: false,
})
export class MyInputComponent {}
// #enddocregion component-input
// #docregion component-output-interval
@Directive({
selector: 'app-interval-dir',
outputs: ['everySecond', 'fiveSecs: everyFiveSeconds'],
standalone: false,
})
export class IntervalDirComponent {
everySecond = new EventEmitter<string>();
fiveSecs = new EventEmitter<string>();
constructor() {
setInterval(() => this.everySecond.emit('event'), 1000);
setInterval(() => this.fiveSecs.emit('event'), 5000);
}
}
@Component({
selector: 'app-my-output',
template: `
<app-interval-dir
(everySecond)="onEverySecond()"
(everyFiveSeconds)="onEveryFiveSeconds()"
></app-interval-dir>
`,
standalone: false,
})
export class MyOutputComponent {
onEverySecond() {
console.log('second');
}
onEveryFiveSeconds() {
console.log('five seconds');
}
}
// #enddocregion component-output-interval
@NgModule({
declarations: [BankAccountComponent, MyInputComponent, IntervalDirComponent, MyOutputComponent],
})
export class AppModule {}
| {
"end_byte": 1958,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/metadata/directives.ts"
} |
angular/adev/src/content/api-examples/core/ts/metadata/metadata.ts_0_1187 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Attribute, Component, Directive, Pipe} from '@angular/core';
class CustomDirective {}
@Component({
selector: 'greet',
template: 'Hello {{name}}!',
standalone: false,
})
class Greet {
name: string = 'World';
}
// #docregion attributeFactory
@Component({
selector: 'page',
template: 'Title: {{title}}',
standalone: false,
})
class Page {
title: string;
constructor(@Attribute('title') title: string) {
this.title = title;
}
}
// #enddocregion
// #docregion attributeMetadata
@Directive({
selector: 'input',
standalone: false,
})
class InputAttrDirective {
constructor(@Attribute('type') type: string) {
// type would be 'text' in this example
}
}
// #enddocregion
@Directive({
selector: 'input',
standalone: false,
})
class InputDirective {
constructor() {
// Add some logic.
}
}
@Pipe({
name: 'lowercase',
standalone: false,
})
class Lowercase {
transform(v: string, args: any[]) {
return v.toLowerCase();
}
}
| {
"end_byte": 1187,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/metadata/metadata.ts"
} |
angular/adev/src/content/api-examples/core/ts/metadata/lifecycle_hooks_spec.ts_0_5321 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
Component,
DoCheck,
Input,
OnChanges,
OnDestroy,
OnInit,
SimpleChanges,
Type,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
(function () {
describe('lifecycle hooks examples', () => {
it('should work with ngOnInit', () => {
// #docregion OnInit
@Component({
selector: 'my-cmp',
template: `
...
`,
standalone: false,
})
class MyComponent implements OnInit {
ngOnInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngOnInit', []]]);
});
it('should work with ngDoCheck', () => {
// #docregion DoCheck
@Component({
selector: 'my-cmp',
template: `
...
`,
standalone: false,
})
class MyComponent implements DoCheck {
ngDoCheck() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngDoCheck', []]]);
});
it('should work with ngAfterContentChecked', () => {
// #docregion AfterContentChecked
@Component({
selector: 'my-cmp',
template: `
...
`,
standalone: false,
})
class MyComponent implements AfterContentChecked {
ngAfterContentChecked() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterContentChecked', []]]);
});
it('should work with ngAfterContentInit', () => {
// #docregion AfterContentInit
@Component({
selector: 'my-cmp',
template: `
...
`,
standalone: false,
})
class MyComponent implements AfterContentInit {
ngAfterContentInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterContentInit', []]]);
});
it('should work with ngAfterViewChecked', () => {
// #docregion AfterViewChecked
@Component({
selector: 'my-cmp',
template: `
...
`,
standalone: false,
})
class MyComponent implements AfterViewChecked {
ngAfterViewChecked() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterViewChecked', []]]);
});
it('should work with ngAfterViewInit', () => {
// #docregion AfterViewInit
@Component({
selector: 'my-cmp',
template: `
...
`,
standalone: false,
})
class MyComponent implements AfterViewInit {
ngAfterViewInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterViewInit', []]]);
});
it('should work with ngOnDestroy', () => {
// #docregion OnDestroy
@Component({
selector: 'my-cmp',
template: `
...
`,
standalone: false,
})
class MyComponent implements OnDestroy {
ngOnDestroy() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngOnDestroy', []]]);
});
it('should work with ngOnChanges', () => {
// #docregion OnChanges
@Component({
selector: 'my-cmp',
template: `
...
`,
standalone: false,
})
class MyComponent implements OnChanges {
@Input() prop: number = 0;
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}
// #enddocregion
const log = createAndLogComponent(MyComponent, ['prop']);
expect(log.length).toBe(1);
expect(log[0][0]).toBe('ngOnChanges');
const changes: SimpleChanges = log[0][1][0];
expect(changes['prop'].currentValue).toBe(true);
});
});
function createAndLogComponent(clazz: Type<any>, inputs: string[] = []): any[] {
const log: any[] = [];
createLoggingSpiesFromProto(clazz, log);
const inputBindings = inputs.map((input) => `[${input}] = true`).join(' ');
@Component({
template: `
<my-cmp ${inputBindings}></my-cmp>
`,
standalone: false,
})
class ParentComponent {}
const fixture = TestBed.configureTestingModule({
declarations: [ParentComponent, clazz],
}).createComponent(ParentComponent);
fixture.detectChanges();
fixture.destroy();
return log;
}
function createLoggingSpiesFromProto(clazz: Type<any>, log: any[]) {
const proto = clazz.prototype;
// For ES2015+ classes, members are not enumerable in the prototype.
Object.getOwnPropertyNames(proto).forEach((method) => {
if (method === 'constructor') {
return;
}
proto[method] = (...args: any[]) => {
log.push([method, args]);
};
});
}
})();
| {
"end_byte": 5321,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/metadata/lifecycle_hooks_spec.ts"
} |
angular/adev/src/content/api-examples/core/ts/metadata/encapsulation.ts_0_720 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, ViewEncapsulation} from '@angular/core';
// #docregion longform
@Component({
selector: 'app-root',
template: `
<h1>Hello World!</h1>
<span class="red">Shadow DOM Rocks!</span>
`,
styles: [
`
:host {
display: block;
border: 1px solid black;
}
h1 {
color: blue;
}
.red {
background-color: red;
}
`,
],
encapsulation: ViewEncapsulation.ShadowDom,
standalone: false,
})
class MyApp {}
// #enddocregion
| {
"end_byte": 720,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/metadata/encapsulation.ts"
} |
angular/adev/src/content/api-examples/core/ts/change_detect/change-detection.ts_0_2472 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* tslint:disable:no-console */
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Input,
NgModule,
} from '@angular/core';
import {FormsModule} from '@angular/forms';
// #docregion mark-for-check
@Component({
selector: 'app-root',
template: `
Number of ticks: {{ numberOfTicks }}
`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class AppComponent {
numberOfTicks = 0;
constructor(private ref: ChangeDetectorRef) {
setInterval(() => {
this.numberOfTicks++;
// require view to be updated
this.ref.markForCheck();
}, 1000);
}
}
// #enddocregion mark-for-check
// #docregion detach
class DataListProvider {
// in a real application the returned data will be different every time
get data() {
return [1, 2, 3, 4, 5];
}
}
@Component({
selector: 'giant-list',
template: `
<li *ngFor="let d of dataProvider.data">Data {{ d }}</li>
`,
standalone: false,
})
class GiantList {
constructor(
private ref: ChangeDetectorRef,
public dataProvider: DataListProvider,
) {
ref.detach();
setInterval(() => {
this.ref.detectChanges();
}, 5000);
}
}
@Component({
selector: 'app',
providers: [DataListProvider],
template: `
<giant-list></giant-list>
`,
standalone: false,
})
class App {}
// #enddocregion detach
// #docregion reattach
class DataProvider {
data = 1;
constructor() {
setInterval(() => {
this.data = 2;
}, 500);
}
}
@Component({
selector: 'live-data',
inputs: ['live'],
template: 'Data: {{dataProvider.data}}',
standalone: false,
})
class LiveData {
constructor(
private ref: ChangeDetectorRef,
public dataProvider: DataProvider,
) {}
@Input()
set live(value: boolean) {
if (value) {
this.ref.reattach();
} else {
this.ref.detach();
}
}
}
@Component({
selector: 'app',
providers: [DataProvider],
template: `
Live Update:
<input type="checkbox" [(ngModel)]="live" />
<live-data [live]="live"></live-data>
`,
standalone: false,
})
class App1 {
live = true;
}
// #enddocregion reattach
@NgModule({declarations: [AppComponent, GiantList, App, LiveData, App1], imports: [FormsModule]})
class CoreExamplesModule {}
| {
"end_byte": 2472,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/ts/change_detect/change-detection.ts"
} |
angular/adev/src/content/api-examples/core/debug/ts/debug_element/debug_element.ts_0_346 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DebugElement} from '@angular/core';
let debugElement: DebugElement = undefined!;
let predicate: any;
debugElement.query(predicate);
| {
"end_byte": 346,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/core/debug/ts/debug_element/debug_element.ts"
} |
angular/adev/src/content/api-examples/testing/ts/testing.ts_0_1646 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
let db: any;
class MyService {}
class MyMockService implements MyService {}
describe('some component', () => {
it('does something', () => {
// This is a test.
});
});
// tslint:disable-next-line:ban
fdescribe('some component', () => {
it('has a test', () => {
// This test will run.
});
});
describe('another component', () => {
it('also has a test', () => {
throw 'This test will not run.';
});
});
xdescribe('some component', () => {
it('has a test', () => {
throw 'This test will not run.';
});
});
describe('another component', () => {
it('also has a test', () => {
// This test will run.
});
});
describe('some component', () => {
// tslint:disable-next-line:ban
fit('has a test', () => {
// This test will run.
});
it('has another test', () => {
throw 'This test will not run.';
});
});
describe('some component', () => {
xit('has a test', () => {
throw 'This test will not run.';
});
it('has another test', () => {
// This test will run.
});
});
describe('some component', () => {
beforeEach(() => {
db.connect();
});
it('uses the db', () => {
// Database is connected.
});
});
describe('some component', () => {
afterEach((done: Function) => {
db.reset().then((_: any) => done());
});
it('uses the db', () => {
// This test can leave the database in a dirty state.
// The afterEach will ensure it gets reset.
});
});
| {
"end_byte": 1646,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/testing/ts/testing.ts"
} |
angular/adev/src/content/api-examples/common/main.ts_0_427 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import 'zone.js/lib/browser/rollup-main';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {TestsAppModule} from './test_module';
platformBrowserDynamic().bootstrapModule(TestsAppModule);
| {
"end_byte": 427,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/main.ts"
} |
angular/adev/src/content/api-examples/common/start-server.js_0_552 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
const protractorUtils = require('@bazel/protractor/protractor-utils');
const protractor = require('protractor');
module.exports = async function (config) {
const {port} = await protractorUtils.runServer(config.workspace, config.server, '--port', []);
const serverUrl = `http://localhost:${port}`;
protractor.browser.baseUrl = serverUrl;
};
| {
"end_byte": 552,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/start-server.js"
} |
angular/adev/src/content/api-examples/common/test_module.ts_0_1551 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import * as locationExample from './location/ts/module';
import * as ngComponentOutletExample from './ngComponentOutlet/ts/module';
import * as ngIfExample from './ngIf/ts/module';
import * as ngTemplateOutletExample from './ngTemplateOutlet/ts/module';
import * as pipesExample from './pipes/ts/module';
@Component({
selector: 'example-app:not(y)',
template: '<router-outlet></router-outlet>',
standalone: false,
})
export class TestsAppComponent {}
@NgModule({
imports: [
locationExample.AppModule,
ngComponentOutletExample.AppModule,
ngIfExample.AppModule,
ngTemplateOutletExample.AppModule,
pipesExample.AppModule,
// Router configuration so that the individual e2e tests can load their
// app components.
RouterModule.forRoot([
{path: 'location', component: locationExample.AppComponent},
{path: 'ngComponentOutlet', component: ngComponentOutletExample.AppComponent},
{path: 'ngIf', component: ngIfExample.AppComponent},
{path: 'ngTemplateOutlet', component: ngTemplateOutletExample.AppComponent},
{path: 'pipes', component: pipesExample.AppComponent},
]),
],
declarations: [TestsAppComponent],
bootstrap: [TestsAppComponent],
})
export class TestsAppModule {}
| {
"end_byte": 1551,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/test_module.ts"
} |
angular/adev/src/content/api-examples/common/ngComponentOutlet/ts/module.ts_0_3039 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
Injectable,
Injector,
Input,
NgModule,
OnInit,
TemplateRef,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
// #docregion SimpleExample
@Component({
selector: 'hello-world',
template: 'Hello World!',
standalone: false,
})
export class HelloWorld {}
@Component({
selector: 'ng-component-outlet-simple-example',
template: `
<ng-container *ngComponentOutlet="HelloWorld"></ng-container>
`,
standalone: false,
})
export class NgComponentOutletSimpleExample {
// This field is necessary to expose HelloWorld to the template.
HelloWorld = HelloWorld;
}
// #enddocregion
// #docregion CompleteExample
@Injectable()
export class Greeter {
suffix = '!';
}
@Component({
selector: 'complete-component',
template: `
{{ label }}:
<ng-content></ng-content>
<ng-content></ng-content>
{{ greeter.suffix }}
`,
standalone: false,
})
export class CompleteComponent {
@Input() label!: string;
constructor(public greeter: Greeter) {}
}
@Component({
selector: 'ng-component-outlet-complete-example',
template: `
<ng-template #ahoj>Ahoj</ng-template>
<ng-template #svet>Svet</ng-template>
<ng-container
*ngComponentOutlet="
CompleteComponent;
inputs: myInputs;
injector: myInjector;
content: myContent
"
></ng-container>
`,
standalone: false,
})
export class NgComponentOutletCompleteExample implements OnInit {
// This field is necessary to expose CompleteComponent to the template.
CompleteComponent = CompleteComponent;
myInputs = {'label': 'Complete'};
myInjector: Injector;
@ViewChild('ahoj', {static: true}) ahojTemplateRef!: TemplateRef<any>;
@ViewChild('svet', {static: true}) svetTemplateRef!: TemplateRef<any>;
myContent?: any[][];
constructor(
injector: Injector,
private vcr: ViewContainerRef,
) {
this.myInjector = Injector.create({
providers: [{provide: Greeter, deps: []}],
parent: injector,
});
}
ngOnInit() {
// Create the projectable content from the templates
this.myContent = [
this.vcr.createEmbeddedView(this.ahojTemplateRef).rootNodes,
this.vcr.createEmbeddedView(this.svetTemplateRef).rootNodes,
];
}
}
// #enddocregion
@Component({
selector: 'example-app',
template: `
<ng-component-outlet-simple-example></ng-component-outlet-simple-example>
<hr />
<ng-component-outlet-complete-example></ng-component-outlet-complete-example>
`,
standalone: false,
})
export class AppComponent {}
@NgModule({
imports: [BrowserModule],
declarations: [
AppComponent,
NgComponentOutletSimpleExample,
NgComponentOutletCompleteExample,
HelloWorld,
CompleteComponent,
],
})
export class AppModule {}
| {
"end_byte": 3039,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/ngComponentOutlet/ts/module.ts"
} |
angular/adev/src/content/api-examples/common/ngComponentOutlet/ts/e2e_test/ngComponentOutlet_spec.ts_0_962 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {$, browser, by, element, ExpectedConditions} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
function waitForElement(selector: string) {
const EC = ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('ngComponentOutlet', () => {
const URL = '/ngComponentOutlet';
afterEach(verifyNoBrowserErrors);
describe('ng-component-outlet-example', () => {
it('should render simple', () => {
browser.get(URL);
waitForElement('ng-component-outlet-simple-example');
expect(element.all(by.css('hello-world')).getText()).toEqual(['Hello World!']);
});
});
});
| {
"end_byte": 962,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/ngComponentOutlet/ts/e2e_test/ngComponentOutlet_spec.ts"
} |
angular/adev/src/content/api-examples/common/location/ts/module.ts_0_879 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {APP_BASE_HREF} from '@angular/common';
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {HashLocationComponent} from './hash_location_component';
import {PathLocationComponent} from './path_location_component';
@Component({
selector: 'example-app',
template: `
<hash-location></hash-location>
<path-location></path-location>
`,
standalone: false,
})
export class AppComponent {}
@NgModule({
declarations: [AppComponent, PathLocationComponent, HashLocationComponent],
providers: [{provide: APP_BASE_HREF, useValue: '/'}],
imports: [BrowserModule],
})
export class AppModule {}
| {
"end_byte": 879,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/location/ts/module.ts"
} |
angular/adev/src/content/api-examples/common/location/ts/path_location_component.ts_0_897 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion LocationComponent
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import {Component} from '@angular/core';
@Component({
selector: 'path-location',
providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}],
template: `
<h1>PathLocationStrategy</h1>
Current URL is:
<code>{{ location.path() }}</code>
<br />
Normalize:
<code>/foo/bar/</code>
is:
<code>{{ location.normalize('foo/bar') }}</code>
<br />
`,
standalone: false,
})
export class PathLocationComponent {
location: Location;
constructor(location: Location) {
this.location = location;
}
}
// #enddocregion
| {
"end_byte": 897,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/location/ts/path_location_component.ts"
} |
angular/adev/src/content/api-examples/common/location/ts/hash_location_component.ts_0_897 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion LocationComponent
import {HashLocationStrategy, Location, LocationStrategy} from '@angular/common';
import {Component} from '@angular/core';
@Component({
selector: 'hash-location',
providers: [Location, {provide: LocationStrategy, useClass: HashLocationStrategy}],
template: `
<h1>HashLocationStrategy</h1>
Current URL is:
<code>{{ location.path() }}</code>
<br />
Normalize:
<code>/foo/bar/</code>
is:
<code>{{ location.normalize('foo/bar') }}</code>
<br />
`,
standalone: false,
})
export class HashLocationComponent {
location: Location;
constructor(location: Location) {
this.location = location;
}
}
// #enddocregion
| {
"end_byte": 897,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/location/ts/hash_location_component.ts"
} |
angular/adev/src/content/api-examples/common/location/ts/e2e_test/location_component_spec.ts_0_958 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {$, browser, by, element, protractor} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
function waitForElement(selector: string) {
const EC = (<any>protractor).ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('Location', () => {
afterEach(verifyNoBrowserErrors);
it('should verify paths', () => {
browser.get('/location/#/bar/baz');
waitForElement('hash-location');
expect(element.all(by.css('path-location code')).get(0).getText()).toEqual('/location');
expect(element.all(by.css('hash-location code')).get(0).getText()).toEqual('/bar/baz');
});
});
| {
"end_byte": 958,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/location/ts/e2e_test/location_component_spec.ts"
} |
angular/adev/src/content/api-examples/common/ngTemplateOutlet/ts/module.ts_0_1351 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
// #docregion NgTemplateOutlet
@Component({
selector: 'ng-template-outlet-example',
template: `
<ng-container *ngTemplateOutlet="greet"></ng-container>
<hr />
<ng-container *ngTemplateOutlet="eng; context: myContext"></ng-container>
<hr />
<ng-container *ngTemplateOutlet="svk; context: myContext"></ng-container>
<hr />
<ng-template #greet><span>Hello</span></ng-template>
<ng-template #eng let-name>
<span>Hello {{ name }}!</span>
</ng-template>
<ng-template #svk let-person="localSk">
<span>Ahoj {{ person }}!</span>
</ng-template>
`,
standalone: false,
})
export class NgTemplateOutletExample {
myContext = {$implicit: 'World', localSk: 'Svet'};
}
// #enddocregion
@Component({
selector: 'example-app',
template: `
<ng-template-outlet-example></ng-template-outlet-example>
`,
standalone: false,
})
export class AppComponent {}
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, NgTemplateOutletExample],
})
export class AppModule {}
| {
"end_byte": 1351,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/ngTemplateOutlet/ts/module.ts"
} |
angular/adev/src/content/api-examples/common/ngTemplateOutlet/ts/e2e_test/ngTemplateOutlet_spec.ts_0_1020 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {$, browser, by, element, ExpectedConditions} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
function waitForElement(selector: string) {
const EC = ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('ngTemplateOutlet', () => {
const URL = '/ngTemplateOutlet';
afterEach(verifyNoBrowserErrors);
describe('ng-template-outlet-example', () => {
it('should render', () => {
browser.get(URL);
waitForElement('ng-template-outlet-example');
expect(element.all(by.css('ng-template-outlet-example span')).getText()).toEqual([
'Hello',
'Hello World!',
'Ahoj Svet!',
]);
});
});
});
| {
"end_byte": 1020,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/ngTemplateOutlet/ts/e2e_test/ngTemplateOutlet_spec.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/percent_pipe.ts_0_894 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {registerLocaleData} from '@angular/common';
import {Component} from '@angular/core';
// we need to import data for the french locale
import localeFr from './locale-fr';
// registering french data
registerLocaleData(localeFr);
// #docregion PercentPipe
@Component({
selector: 'percent-pipe',
template: `
<div>
<!--output '26%'-->
<p>A: {{ a | percent }}</p>
<!--output '0,134.950%'-->
<p>B: {{ b | percent : '4.3-5' }}</p>
<!--output '0 134,950 %'-->
<p>B: {{ b | percent : '4.3-5' : 'fr' }}</p>
</div>
`,
standalone: false,
})
export class PercentPipeComponent {
a: number = 0.259;
b: number = 1.3495;
}
// #enddocregion
| {
"end_byte": 894,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/percent_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/locale-fr.ts_0_2674 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
let i = Math.floor(Math.abs(n));
if (i === 0 || i === 1) return 1;
return 5;
}
export default [
'fr',
[['AM', 'PM'], u, u],
u,
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'],
['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
['di', 'lu', 'ma', 'me', 'je', 've', 'sa'],
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'janv.',
'févr.',
'mars',
'avr.',
'mai',
'juin',
'juil.',
'août',
'sept.',
'oct.',
'nov.',
'déc.',
],
[
'janvier',
'février',
'mars',
'avril',
'mai',
'juin',
'juillet',
'août',
'septembre',
'octobre',
'novembre',
'décembre',
],
],
u,
[['av. J.-C.', 'ap. J.-C.'], u, ['avant Jésus-Christ', 'après Jésus-Christ']],
1,
[6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', "{1} 'à' {0}", u, u],
[',', '\u202f', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'],
'EUR',
'€',
'euro',
{
'ARS': ['$AR', '$'],
'AUD': ['$AU', '$'],
'BEF': ['FB'],
'BMD': ['$BM', '$'],
'BND': ['$BN', '$'],
'BZD': ['$BZ', '$'],
'CAD': ['$CA', '$'],
'CLP': ['$CL', '$'],
'CNY': [u, '¥'],
'COP': ['$CO', '$'],
'CYP': ['£CY'],
'EGP': [u, '£E'],
'FJD': ['$FJ', '$'],
'FKP': ['£FK', '£'],
'FRF': ['F'],
'GBP': ['£GB', '£'],
'GIP': ['£GI', '£'],
'HKD': [u, '$'],
'IEP': ['£IE'],
'ILP': ['£IL'],
'ITL': ['₤IT'],
'JPY': [u, '¥'],
'KMF': [u, 'FC'],
'LBP': ['£LB', '£L'],
'MTP': ['£MT'],
'MXN': ['$MX', '$'],
'NAD': ['$NA', '$'],
'NIO': [u, '$C'],
'NZD': ['$NZ', '$'],
'RHD': ['$RH'],
'RON': [u, 'L'],
'RWF': [u, 'FR'],
'SBD': ['$SB', '$'],
'SGD': ['$SG', '$'],
'SRD': ['$SR', '$'],
'TOP': [u, '$T'],
'TTD': ['$TT', '$'],
'TWD': [u, 'NT$'],
'USD': ['$US', '$'],
'UYU': ['$UY', '$'],
'WST': ['$WS'],
'XCD': [u, '$'],
'XPF': ['FCFP'],
'ZMW': [u, 'Kw'],
},
'ltr',
plural,
];
| {
"end_byte": 2674,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/locale-fr.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/currency_pipe.ts_0_1300 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {registerLocaleData} from '@angular/common';
import {Component} from '@angular/core';
// we need to import data for the french locale
import localeFr from './locale-fr';
// registering french data
registerLocaleData(localeFr);
// #docregion CurrencyPipe
@Component({
selector: 'currency-pipe',
template: `
<div>
<!--output '$0.26'-->
<p>A: {{ a | currency }}</p>
<!--output 'CA$0.26'-->
<p>A: {{ a | currency : 'CAD' }}</p>
<!--output 'CAD0.26'-->
<p>A: {{ a | currency : 'CAD' : 'code' }}</p>
<!--output 'CA$0,001.35'-->
<p>B: {{ b | currency : 'CAD' : 'symbol' : '4.2-2' }}</p>
<!--output '$0,001.35'-->
<p>B: {{ b | currency : 'CAD' : 'symbol-narrow' : '4.2-2' }}</p>
<!--output '0 001,35 CA$'-->
<p>B: {{ b | currency : 'CAD' : 'symbol' : '4.2-2' : 'fr' }}</p>
<!--output 'CLP1' because CLP has no cents-->
<p>B: {{ b | currency : 'CLP' }}</p>
</div>
`,
standalone: false,
})
export class CurrencyPipeComponent {
a: number = 0.259;
b: number = 1.3495;
}
// #enddocregion
| {
"end_byte": 1300,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/currency_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/module.ts_0_2566 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AsyncObservablePipeComponent, AsyncPromisePipeComponent} from './async_pipe';
import {CurrencyPipeComponent} from './currency_pipe';
import {DatePipeComponent, DeprecatedDatePipeComponent} from './date_pipe';
import {I18nPluralPipeComponent, I18nSelectPipeComponent} from './i18n_pipe';
import {JsonPipeComponent} from './json_pipe';
import {KeyValuePipeComponent} from './keyvalue_pipe';
import {LowerUpperPipeComponent} from './lowerupper_pipe';
import {NumberPipeComponent} from './number_pipe';
import {PercentPipeComponent} from './percent_pipe';
import {SlicePipeListComponent, SlicePipeStringComponent} from './slice_pipe';
import {TitleCasePipeComponent} from './titlecase_pipe';
@Component({
selector: 'example-app',
template: `
<h1>Pipe Example</h1>
<h2><code>async</code></h2>
<async-promise-pipe></async-promise-pipe>
<async-observable-pipe></async-observable-pipe>
<h2><code>date</code></h2>
<date-pipe></date-pipe>
<h2><code>json</code></h2>
<json-pipe></json-pipe>
<h2>
<code>lower</code>
,
<code>upper</code>
</h2>
<lowerupper-pipe></lowerupper-pipe>
<h2><code>titlecase</code></h2>
<titlecase-pipe></titlecase-pipe>
<h2><code>number</code></h2>
<number-pipe></number-pipe>
<percent-pipe></percent-pipe>
<currency-pipe></currency-pipe>
<h2><code>slice</code></h2>
<slice-string-pipe></slice-string-pipe>
<slice-list-pipe></slice-list-pipe>
<h2><code>i18n</code></h2>
<i18n-plural-pipe></i18n-plural-pipe>
<i18n-select-pipe></i18n-select-pipe>
<h2><code>keyvalue</code></h2>
<keyvalue-pipe></keyvalue-pipe>
`,
standalone: false,
})
export class AppComponent {}
@NgModule({
declarations: [
AsyncPromisePipeComponent,
AsyncObservablePipeComponent,
AppComponent,
JsonPipeComponent,
DatePipeComponent,
DeprecatedDatePipeComponent,
LowerUpperPipeComponent,
TitleCasePipeComponent,
NumberPipeComponent,
PercentPipeComponent,
CurrencyPipeComponent,
SlicePipeStringComponent,
SlicePipeListComponent,
I18nPluralPipeComponent,
I18nSelectPipeComponent,
KeyValuePipeComponent,
],
imports: [BrowserModule],
})
export class AppModule {}
| {
"end_byte": 2566,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/module.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/async_pipe.ts_0_2046 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
import {Observable, Observer} from 'rxjs';
// #docregion AsyncPipePromise
@Component({
selector: 'async-promise-pipe',
template: `
<div>
<code>promise|async</code>
:
<button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
<span>Wait for it... {{ greeting | async }}</span>
</div>
`,
standalone: false,
})
export class AsyncPromisePipeComponent {
greeting: Promise<string> | null = null;
arrived: boolean = false;
private resolve: Function | null = null;
constructor() {
this.reset();
}
reset() {
this.arrived = false;
this.greeting = new Promise<string>((resolve, reject) => {
this.resolve = resolve;
});
}
clicked() {
if (this.arrived) {
this.reset();
} else {
this.resolve!('hi there!');
this.arrived = true;
}
}
}
// #enddocregion
// #docregion AsyncPipeObservable
@Component({
selector: 'async-observable-pipe',
template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>',
standalone: false,
})
export class AsyncObservablePipeComponent {
time = new Observable<string>((observer: Observer<string>) => {
setInterval(() => observer.next(new Date().toString()), 1000);
});
}
// #enddocregion
// For some reason protractor hangs on setInterval. So we will run outside of angular zone so that
// protractor will not see us. Also we want to have this outside the docregion so as not to confuse
// the reader.
function setInterval(fn: Function, delay: number) {
const zone = (window as any)['Zone'].current;
let rootZone = zone;
while (rootZone.parent) {
rootZone = rootZone.parent;
}
rootZone.run(() => {
window.setInterval(function (this: unknown) {
zone.run(fn, this, arguments as any);
}, delay);
});
}
| {
"end_byte": 2046,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/async_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/lowerupper_pipe.ts_0_747 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
// #docregion LowerUpperPipe
@Component({
selector: 'lowerupper-pipe',
template: `
<div>
<label>Name:</label>
<input #name (keyup)="change(name.value)" type="text" />
<p>In lowercase:</p>
<pre>'{{ value | lowercase }}'</pre>
<p>In uppercase:</p>
<pre>'{{ value | uppercase }}'</pre>
</div>
`,
standalone: false,
})
export class LowerUpperPipeComponent {
value: string = '';
change(value: string) {
this.value = value;
}
}
// #enddocregion
| {
"end_byte": 747,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/lowerupper_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/slice_pipe.ts_0_1324 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
// #docregion SlicePipe_string
@Component({
selector: 'slice-string-pipe',
template: `
<div>
<p>{{ str }}[0:4]: '{{ str | slice : 0 : 4 }}' - output is expected to be 'abcd'</p>
<p>{{ str }}[4:0]: '{{ str | slice : 4 : 0 }}' - output is expected to be ''</p>
<p>{{ str }}[-4]: '{{ str | slice : -4 }}' - output is expected to be 'ghij'</p>
<p>{{ str }}[-4:-2]: '{{ str | slice : -4 : -2 }}' - output is expected to be 'gh'</p>
<p>{{ str }}[-100]: '{{ str | slice : -100 }}' - output is expected to be 'abcdefghij'</p>
<p>{{ str }}[100]: '{{ str | slice : 100 }}' - output is expected to be ''</p>
</div>
`,
standalone: false,
})
export class SlicePipeStringComponent {
str: string = 'abcdefghij';
}
// #enddocregion
// #docregion SlicePipe_list
@Component({
selector: 'slice-list-pipe',
template: `
<ul>
<li *ngFor="let i of collection | slice : 1 : 3">{{ i }}</li>
</ul>
`,
standalone: false,
})
export class SlicePipeListComponent {
collection: string[] = ['a', 'b', 'c', 'd'];
}
// #enddocregion
| {
"end_byte": 1324,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/slice_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/keyvalue_pipe.ts_0_879 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
// #docregion KeyValuePipe
@Component({
selector: 'keyvalue-pipe',
template: `
<span>
<p>Object</p>
<div *ngFor="let item of object | keyvalue">{{ item.key }}:{{ item.value }}</div>
<p>Map</p>
<div *ngFor="let item of map | keyvalue">{{ item.key }}:{{ item.value }}</div>
<p>Natural order</p>
<div *ngFor="let item of map | keyvalue: null">{{ item.key }}:{{ item.value }}</div>
</span>
`,
standalone: false,
})
export class KeyValuePipeComponent {
object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
map = new Map([
[2, 'foo'],
[1, 'bar'],
]);
}
// #enddocregion
| {
"end_byte": 879,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/keyvalue_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/titlecase_pipe.ts_0_1073 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
// #docregion TitleCasePipe
@Component({
selector: 'titlecase-pipe',
template: `
<div>
<p>{{ 'some string' | titlecase }}</p>
<!-- output is expected to be "Some String" -->
<p>{{ 'tHIs is mIXeD CaSe' | titlecase }}</p>
<!-- output is expected to be "This Is Mixed Case" -->
<p>{{ "it's non-trivial question" | titlecase }}</p>
<!-- output is expected to be "It's Non-trivial Question" -->
<p>{{ 'one,two,three' | titlecase }}</p>
<!-- output is expected to be "One,two,three" -->
<p>{{ 'true|false' | titlecase }}</p>
<!-- output is expected to be "True|false" -->
<p>{{ 'foo-vs-bar' | titlecase }}</p>
<!-- output is expected to be "Foo-vs-bar" -->
</div>
`,
standalone: false,
})
export class TitleCasePipeComponent {}
// #enddocregion
| {
"end_byte": 1073,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/titlecase_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/i18n_pipe.ts_0_1019 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
// #docregion I18nPluralPipeComponent
@Component({
selector: 'i18n-plural-pipe',
template: `
<div>{{ messages.length | i18nPlural : messageMapping }}</div>
`,
standalone: false,
})
export class I18nPluralPipeComponent {
messages: any[] = ['Message 1'];
messageMapping: {[k: string]: string} = {
'=0': 'No messages.',
'=1': 'One message.',
'other': '# messages.',
};
}
// #enddocregion
// #docregion I18nSelectPipeComponent
@Component({
selector: 'i18n-select-pipe',
template: `
<div>{{ gender | i18nSelect : inviteMap }}</div>
`,
standalone: false,
})
export class I18nSelectPipeComponent {
gender: string = 'male';
inviteMap: any = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'};
}
//#enddocregion
| {
"end_byte": 1019,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/i18n_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/date_pipe.ts_0_2097 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {registerLocaleData} from '@angular/common';
import {Component} from '@angular/core';
// we need to import data for the french locale
import localeFr from './locale-fr';
// registering french data
registerLocaleData(localeFr);
@Component({
selector: 'date-pipe',
template: `
<div>
<!--output 'Jun 15, 2015'-->
<p>Today is {{ today | date }}</p>
<!--output 'Monday, June 15, 2015'-->
<p>Or if you prefer, {{ today | date : 'fullDate' }}</p>
<!--output '9:43 AM'-->
<p>The time is {{ today | date : 'shortTime' }}</p>
<!--output 'Monday, June 15, 2015 at 9:03:01 AM GMT+01:00' -->
<p>The full date/time is {{ today | date : 'full' }}</p>
<!--output 'Lundi 15 Juin 2015 à 09:03:01 GMT+01:00'-->
<p>The full date/time in french is: {{ today | date : 'full' : '' : 'fr' }}</p>
<!--output '2015-06-15 05:03 PM GMT+9'-->
<p>The custom date is {{ today | date : 'yyyy-MM-dd HH:mm a z' : '+0900' }}</p>
<!--output '2015-06-15 09:03 AM GMT+9'-->
<p>
The custom date with fixed timezone is
{{ fixedTimezone | date : 'yyyy-MM-dd HH:mm a z' : '+0900' }}
</p>
</div>
`,
standalone: false,
})
export class DatePipeComponent {
today = Date.now();
fixedTimezone = '2015-06-15T09:03:01+0900';
}
@Component({
selector: 'deprecated-date-pipe',
template: `
<div>
<!--output 'Sep 3, 2010'-->
<p>Today is {{ today | date }}</p>
<!--output 'Friday, September 3, 2010'-->
<p>Or if you prefer, {{ today | date : 'fullDate' }}</p>
<!--output '12:05 PM'-->
<p>The time is {{ today | date : 'shortTime' }}</p>
<!--output '2010-09-03 12:05 PM'-->
<p>The custom date is {{ today | date : 'yyyy-MM-dd HH:mm a' }}</p>
</div>
`,
standalone: false,
})
export class DeprecatedDatePipeComponent {
today = Date.now();
}
| {
"end_byte": 2097,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/date_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/json_pipe.ts_0_640 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
// #docregion JsonPipe
@Component({
selector: 'json-pipe',
template: `
<div>
<p>Without JSON pipe:</p>
<pre>{{ object }}</pre>
<p>With JSON pipe:</p>
<pre>{{ object | json }}</pre>
</div>
`,
standalone: false,
})
export class JsonPipeComponent {
object: Object = {foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}};
}
// #enddocregion
| {
"end_byte": 640,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/json_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/number_pipe.ts_0_1044 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {registerLocaleData} from '@angular/common';
import {Component} from '@angular/core';
// we need to import data for the french locale
import localeFr from './locale-fr';
registerLocaleData(localeFr, 'fr');
// #docregion NumberPipe
@Component({
selector: 'number-pipe',
template: `
<div>
<p>
No specified formatting:
{{ pi | number }}
<!--output: '3.142'-->
</p>
<p>
With digitsInfo parameter specified:
{{ pi | number : '4.1-5' }}
<!--output: '0,003.14159'-->
</p>
<p>
With digitsInfo and locale parameters specified:
{{ pi | number : '4.1-5' : 'fr' }}
<!--output: '0 003,14159'-->
</p>
</div>
`,
standalone: false,
})
export class NumberPipeComponent {
pi: number = 3.14159265359;
}
// #enddocregion
| {
"end_byte": 1044,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/number_pipe.ts"
} |
angular/adev/src/content/api-examples/common/pipes/ts/e2e_test/pipe_spec.ts_0_4452 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {$, browser, by, element, ExpectedConditions} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index';
function waitForElement(selector: string) {
const EC = ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('pipe', () => {
afterEach(verifyNoBrowserErrors);
const URL = '/pipes';
describe('async', () => {
it('should resolve and display promise', () => {
browser.get(URL);
waitForElement('async-promise-pipe');
expect(element.all(by.css('async-promise-pipe span')).get(0).getText()).toEqual(
'Wait for it...',
);
element(by.css('async-promise-pipe button')).click();
expect(element.all(by.css('async-promise-pipe span')).get(0).getText()).toEqual(
'Wait for it... hi there!',
);
});
});
describe('lowercase/uppercase', () => {
it('should work properly', () => {
browser.get(URL);
waitForElement('lowerupper-pipe');
element(by.css('lowerupper-pipe input')).sendKeys('Hello World!');
expect(element.all(by.css('lowerupper-pipe pre')).get(0).getText()).toEqual("'hello world!'");
expect(element.all(by.css('lowerupper-pipe pre')).get(1).getText()).toEqual("'HELLO WORLD!'");
});
});
describe('titlecase', () => {
it('should work properly', () => {
browser.get(URL);
waitForElement('titlecase-pipe');
expect(element.all(by.css('titlecase-pipe p')).get(0).getText()).toEqual('Some String');
expect(element.all(by.css('titlecase-pipe p')).get(1).getText()).toEqual(
'This Is Mixed Case',
);
expect(element.all(by.css('titlecase-pipe p')).get(2).getText()).toEqual(
"It's Non-trivial Question",
);
expect(element.all(by.css('titlecase-pipe p')).get(3).getText()).toEqual('One,two,three');
expect(element.all(by.css('titlecase-pipe p')).get(4).getText()).toEqual('True|false');
expect(element.all(by.css('titlecase-pipe p')).get(5).getText()).toEqual('Foo-vs-bar');
});
});
describe('keyvalue', () => {
it('should work properly', () => {
browser.get(URL);
waitForElement('keyvalue-pipe');
expect(element.all(by.css('keyvalue-pipe div')).get(0).getText()).toEqual('1:bar');
expect(element.all(by.css('keyvalue-pipe div')).get(1).getText()).toEqual('2:foo');
expect(element.all(by.css('keyvalue-pipe div')).get(2).getText()).toEqual('1:bar');
expect(element.all(by.css('keyvalue-pipe div')).get(3).getText()).toEqual('2:foo');
});
});
describe('number', () => {
it('should work properly', () => {
browser.get(URL);
waitForElement('number-pipe');
const examples = element.all(by.css('number-pipe p'));
expect(examples.get(0).getText()).toEqual('No specified formatting: 3.142');
expect(examples.get(1).getText()).toEqual('With digitsInfo parameter specified: 0,003.14159');
expect(examples.get(2).getText()).toEqual(
'With digitsInfo and locale parameters specified: 0\u202f003,14159',
);
});
});
describe('percent', () => {
it('should work properly', () => {
browser.get(URL);
waitForElement('percent-pipe');
const examples = element.all(by.css('percent-pipe p'));
expect(examples.get(0).getText()).toEqual('A: 26%');
expect(examples.get(1).getText()).toEqual('B: 0,134.950%');
expect(examples.get(2).getText()).toEqual('B: 0\u202f134,950 %');
});
});
describe('currency', () => {
it('should work properly', () => {
browser.get(URL);
waitForElement('currency-pipe');
const examples = element.all(by.css('currency-pipe p'));
expect(examples.get(0).getText()).toEqual('A: $0.26');
expect(examples.get(1).getText()).toEqual('A: CA$0.26');
expect(examples.get(2).getText()).toEqual('A: CAD0.26');
expect(examples.get(3).getText()).toEqual('B: CA$0,001.35');
expect(examples.get(4).getText()).toEqual('B: $0,001.35');
expect(examples.get(5).getText()).toEqual('B: 0\u202f001,35 $CA');
expect(examples.get(6).getText()).toEqual('B: CLP1');
});
});
});
| {
"end_byte": 4452,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/common/pipes/ts/e2e_test/pipe_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.