_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_72298_79356
it('should call `$postLink()` on controller', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const $postLinkSpyA = jasmine.createSpy('$postLinkA'); const $postLinkSpyB = jasmine.createSpy('$postLinkB'); @Component({ selector: 'ng2', template: '<ng1-a></ng1-a> | <ng1-b></ng1-b>', standalone: false, }) class Ng2Component {} angular .module_('ng1', []) .directive('ng1A', () => ({ template: '', scope: {}, bindToController: true, controllerAs: '$ctrl', controller: class { $postLink() { $postLinkSpyA(); } }, })) .directive('ng1B', () => ({ template: '', scope: {}, bindToController: false, controllerAs: '$ctrl', controller: function (this: any) { this.$postLink = $postLinkSpyB; }, })) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); @NgModule({ declarations: [ adapter.upgradeNg1Component('ng1A'), adapter.upgradeNg1Component('ng1B'), Ng2Component, ], imports: [BrowserModule], }) class Ng2Module {} const element = html(`<div><ng2></ng2></div>`); adapter.bootstrap(element, ['ng1']).ready((ref) => { expect($postLinkSpyA).toHaveBeenCalled(); expect($postLinkSpyB).toHaveBeenCalled(); ref.dispose(); }); })); it('should not call `$postLink()` on scope', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const $postLinkSpy = jasmine.createSpy('$postLink'); @Component({ selector: 'ng2', template: '<ng1-a></ng1-a> | <ng1-b></ng1-b>', standalone: false, }) class Ng2Component {} angular .module_('ng1', []) .directive('ng1A', () => ({ template: '', scope: {}, bindToController: true, controllerAs: '$ctrl', controller: function ($scope: angular.IScope) { Object.getPrototypeOf($scope).$postLink = $postLinkSpy; }, })) .directive('ng1B', () => ({ template: '', scope: {}, bindToController: false, controllerAs: '$ctrl', controller: function ($scope: angular.IScope) { $scope['$postLink'] = $postLinkSpy; }, })) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); @NgModule({ declarations: [ adapter.upgradeNg1Component('ng1A'), adapter.upgradeNg1Component('ng1B'), Ng2Component, ], imports: [BrowserModule], }) class Ng2Module {} const element = html(`<div><ng2></ng2></div>`); adapter.bootstrap(element, ['ng1']).ready((ref) => { expect($postLinkSpy).not.toHaveBeenCalled(); ref.dispose(); }); })); it('should call `$onChanges()` on binding destination', fakeAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const $onChangesControllerSpyA = jasmine.createSpy('$onChangesControllerA'); const $onChangesControllerSpyB = jasmine.createSpy('$onChangesControllerB'); const $onChangesScopeSpy = jasmine.createSpy('$onChangesScope'); let ng2Instance: any; @Component({ selector: 'ng2', template: '<ng1-a [valA]="val"></ng1-a> | <ng1-b [valB]="val"></ng1-b>', standalone: false, }) class Ng2Component { constructor() { ng2Instance = this; } } angular .module_('ng1', []) .directive('ng1A', () => ({ template: '', scope: {valA: '<'}, bindToController: true, controllerAs: '$ctrl', controller: function (this: any, $scope: angular.IScope) { this.$onChanges = $onChangesControllerSpyA; }, })) .directive('ng1B', () => ({ template: '', scope: {valB: '<'}, bindToController: false, controllerAs: '$ctrl', controller: class { $onChanges(changes: SimpleChanges) { $onChangesControllerSpyB(changes); } }, })) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)) .run(($rootScope: angular.IRootScopeService) => { Object.getPrototypeOf($rootScope).$onChanges = $onChangesScopeSpy; }); @NgModule({ declarations: [ adapter.upgradeNg1Component('ng1A'), adapter.upgradeNg1Component('ng1B'), Ng2Component, ], imports: [BrowserModule], }) class Ng2Module {} const element = html(`<div><ng2></ng2></div>`); adapter.bootstrap(element, ['ng1']).ready((ref) => { // Initial `$onChanges()` call tick(); expect($onChangesControllerSpyA.calls.count()).toBe(1); expect($onChangesControllerSpyA.calls.argsFor(0)[0]).toEqual({ valA: jasmine.any(SimpleChange), }); expect($onChangesControllerSpyB).not.toHaveBeenCalled(); expect($onChangesScopeSpy.calls.count()).toBe(1); expect($onChangesScopeSpy.calls.argsFor(0)[0]).toEqual({ valB: jasmine.any(SimpleChange), }); $onChangesControllerSpyA.calls.reset(); $onChangesControllerSpyB.calls.reset(); $onChangesScopeSpy.calls.reset(); // `$onChanges()` call after a change ng2Instance.val = 'new value'; tick(); ref.ng1RootScope.$digest(); expect($onChangesControllerSpyA.calls.count()).toBe(1); expect($onChangesControllerSpyA.calls.argsFor(0)[0]).toEqual({ valA: jasmine.objectContaining({currentValue: 'new value'}), }); expect($onChangesControllerSpyB).not.toHaveBeenCalled(); expect($onChangesScopeSpy.calls.count()).toBe(1); expect($onChangesScopeSpy.calls.argsFor(0)[0]).toEqual({ valB: jasmine.objectContaining({currentValue: 'new value'}), }); ref.dispose(); }); }));
{ "end_byte": 79356, "start_byte": 72298, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts" }
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_79366_85400
it('should call `$onDestroy()` on controller', fakeAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const $onDestroySpyA = jasmine.createSpy('$onDestroyA'); const $onDestroySpyB = jasmine.createSpy('$onDestroyB'); let ng2ComponentInstance: Ng2Component; @Component({ selector: 'ng2', template: ` <div *ngIf="!ng2Destroy"><ng1-a></ng1-a> | <ng1-b></ng1-b></div> `, standalone: false, }) class Ng2Component { ng2Destroy: boolean = false; constructor() { ng2ComponentInstance = this; } } // On browsers that don't support `requestAnimationFrame` (Android <= 4.3), // `$animate` will use `setTimeout(..., 16.6)` instead. This timeout will still be // on // the queue at the end of the test, causing it to fail. // Mocking animations (via `ngAnimateMock`) avoids the issue. angular .module_('ng1', ['ngAnimateMock']) .directive('ng1A', () => ({ template: '', scope: {}, bindToController: true, controllerAs: '$ctrl', controller: class { $onDestroy() { $onDestroySpyA(); } }, })) .directive('ng1B', () => ({ template: '', scope: {}, bindToController: false, controllerAs: '$ctrl', controller: function (this: any) { this.$onDestroy = $onDestroySpyB; }, })) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); @NgModule({ declarations: [ adapter.upgradeNg1Component('ng1A'), adapter.upgradeNg1Component('ng1B'), Ng2Component, ], imports: [BrowserModule], }) class Ng2Module {} const element = html(`<div ng-if="!ng1Destroy"><ng2></ng2></div>`); adapter.bootstrap(element, ['ng1']).ready((ref) => { const $rootScope = ref.ng1RootScope as any; $rootScope.ng1Destroy = false; tick(); $rootScope.$digest(); expect($onDestroySpyA).not.toHaveBeenCalled(); expect($onDestroySpyB).not.toHaveBeenCalled(); $rootScope.ng1Destroy = true; tick(); $rootScope.$digest(); expect($onDestroySpyA).toHaveBeenCalled(); expect($onDestroySpyB).toHaveBeenCalled(); $onDestroySpyA.calls.reset(); $onDestroySpyB.calls.reset(); $rootScope.ng1Destroy = false; tick(); $rootScope.$digest(); expect($onDestroySpyA).not.toHaveBeenCalled(); expect($onDestroySpyB).not.toHaveBeenCalled(); ng2ComponentInstance.ng2Destroy = true; tick(); $rootScope.$digest(); expect($onDestroySpyA).toHaveBeenCalled(); expect($onDestroySpyB).toHaveBeenCalled(); ref.dispose(); }); })); it('should not call `$onDestroy()` on scope', fakeAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const $onDestroySpy = jasmine.createSpy('$onDestroy'); let ng2ComponentInstance: Ng2Component; @Component({ selector: 'ng2', template: ` <div *ngIf="!ng2Destroy"><ng1-a></ng1-a> | <ng1-b></ng1-b></div> `, standalone: false, }) class Ng2Component { ng2Destroy: boolean = false; constructor() { ng2ComponentInstance = this; } } // On browsers that don't support `requestAnimationFrame` (Android <= 4.3), // `$animate` will use `setTimeout(..., 16.6)` instead. This timeout will still be // on // the queue at the end of the test, causing it to fail. // Mocking animations (via `ngAnimateMock`) avoids the issue. angular .module_('ng1', ['ngAnimateMock']) .directive('ng1A', () => ({ template: '', scope: {}, bindToController: true, controllerAs: '$ctrl', controller: function ($scope: angular.IScope) { Object.getPrototypeOf($scope).$onDestroy = $onDestroySpy; }, })) .directive('ng1B', () => ({ template: '', scope: {}, bindToController: false, controllerAs: '$ctrl', controller: function ($scope: angular.IScope) { $scope['$onDestroy'] = $onDestroySpy; }, })) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); @NgModule({ declarations: [ adapter.upgradeNg1Component('ng1A'), adapter.upgradeNg1Component('ng1B'), Ng2Component, ], imports: [BrowserModule], }) class Ng2Module {} const element = html(`<div ng-if="!ng1Destroy"><ng2></ng2></div>`); adapter.bootstrap(element, ['ng1']).ready((ref) => { const $rootScope = ref.ng1RootScope as any; $rootScope.ng1Destroy = false; tick(); $rootScope.$digest(); $rootScope.ng1Destroy = true; tick(); $rootScope.$digest(); $rootScope.ng1Destroy = false; tick(); $rootScope.$digest(); ng2ComponentInstance.ng2Destroy = true; tick(); $rootScope.$digest(); expect($onDestroySpy).not.toHaveBeenCalled(); ref.dispose(); }); })); });
{ "end_byte": 85400, "start_byte": 79366, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts" }
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_85408_95009
describe('destroying the upgraded component', () => { it('should destroy `componentScope`', fakeAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const scopeDestroyListener = jasmine.createSpy('scopeDestroyListener'); let ng2ComponentInstance: Ng2Component; @Component({ selector: 'ng2', template: '<div *ngIf="!ng2Destroy"><ng1></ng1></div>', standalone: false, }) class Ng2Component { ng2Destroy: boolean = false; constructor() { ng2ComponentInstance = this; } } // On browsers that don't support `requestAnimationFrame` (Android <= 4.3), // `$animate` will use `setTimeout(..., 16.6)` instead. This timeout will still be // on // the queue at the end of the test, causing it to fail. // Mocking animations (via `ngAnimateMock`) avoids the issue. angular .module_('ng1', ['ngAnimateMock']) .component('ng1', { controller: function ($scope: angular.IScope) { $scope.$on('$destroy', scopeDestroyListener); }, }) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); @NgModule({ declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], imports: [BrowserModule], }) class Ng2Module {} const element = html('<ng2></ng2>'); adapter.bootstrap(element, ['ng1']).ready((ref) => { const $rootScope = ref.ng1RootScope as any; expect(scopeDestroyListener).not.toHaveBeenCalled(); ng2ComponentInstance.ng2Destroy = true; tick(); $rootScope.$digest(); expect(scopeDestroyListener).toHaveBeenCalledTimes(1); }); })); it('should emit `$destroy` on `$element` and descendants', fakeAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const elementDestroyListener = jasmine.createSpy('elementDestroyListener'); const descendantDestroyListener = jasmine.createSpy('descendantDestroyListener'); let ng2ComponentInstance: Ng2Component; @Component({ selector: 'ng2', template: '<div *ngIf="!ng2Destroy"><ng1></ng1></div>', standalone: false, }) class Ng2Component { ng2Destroy: boolean = false; constructor() { ng2ComponentInstance = this; } } // On browsers that don't support `requestAnimationFrame` (Android <= 4.3), // `$animate` will use `setTimeout(..., 16.6)` instead. This timeout will still be // on the queue at the end of the test, causing it to fail. // Mocking animations (via `ngAnimateMock`) avoids the issue. angular .module_('ng1', ['ngAnimateMock']) .component('ng1', { controller: class { constructor(private $element: angular.IAugmentedJQuery) {} $onInit() { this.$element.on!('$destroy', elementDestroyListener); this.$element.contents!().on!('$destroy', descendantDestroyListener); } }, template: '<div></div>', }) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); @NgModule({ declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], imports: [BrowserModule], }) class Ng2Module {} const element = html('<ng2></ng2>'); adapter.bootstrap(element, ['ng1']).ready((ref) => { const $rootScope = ref.ng1RootScope as any; tick(); $rootScope.$digest(); expect(elementDestroyListener).not.toHaveBeenCalled(); expect(descendantDestroyListener).not.toHaveBeenCalled(); ng2ComponentInstance.ng2Destroy = true; tick(); $rootScope.$digest(); expect(elementDestroyListener).toHaveBeenCalledTimes(1); expect(descendantDestroyListener).toHaveBeenCalledTimes(1); }); })); it('should clear data on `$element` and descendants', fakeAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); let ng1ComponentElement: angular.IAugmentedJQuery; let ng2ComponentAInstance: Ng2ComponentA; // Define `ng1Component` const ng1Component: angular.IComponent = { controller: class { constructor(private $element: angular.IAugmentedJQuery) {} $onInit() { this.$element.data!('test', 1); this.$element.contents!().data!('test', 2); ng1ComponentElement = this.$element; } }, template: '<div></div>', }; // Define `Ng2Component` @Component({ selector: 'ng2A', template: '<ng2B *ngIf="!destroyIt"></ng2B>', standalone: false, }) class Ng2ComponentA { destroyIt = false; constructor() { ng2ComponentAInstance = this; } } @Component({ selector: 'ng2B', template: '<ng1></ng1>', standalone: false, }) class Ng2ComponentB {} // Define `ng1Module` angular .module_('ng1Module', []) .component('ng1', ng1Component) .directive('ng2A', adapter.downgradeNg2Component(Ng2ComponentA)); // Define `Ng2Module` @NgModule({ declarations: [adapter.upgradeNg1Component('ng1'), Ng2ComponentA, Ng2ComponentB], imports: [BrowserModule], }) class Ng2Module { ngDoBootstrap() {} } // Bootstrap const element = html(`<ng2-a></ng2-a>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { const $rootScope = ref.ng1RootScope as any; tick(); $rootScope.$digest(); expect(ng1ComponentElement.data!('test')).toBe(1); expect(ng1ComponentElement.contents!().data!('test')).toBe(2); ng2ComponentAInstance.destroyIt = true; tick(); $rootScope.$digest(); expect(ng1ComponentElement.data!('test')).toBeUndefined(); expect(ng1ComponentElement.contents!().data!('test')).toBeUndefined(); }); })); it('should clear dom listeners on `$element` and descendants`', fakeAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const elementClickListener = jasmine.createSpy('elementClickListener'); const descendantClickListener = jasmine.createSpy('descendantClickListener'); let ng1DescendantElement: angular.IAugmentedJQuery; let ng2ComponentAInstance: Ng2ComponentA; // Define `ng1Component` const ng1Component: angular.IComponent = { controller: class { constructor(private $element: angular.IAugmentedJQuery) {} $onInit() { ng1DescendantElement = this.$element.contents!(); this.$element.on!('click', elementClickListener); ng1DescendantElement.on!('click', descendantClickListener); } }, template: '<div></div>', }; // Define `Ng2Component` @Component({ selector: 'ng2A', template: '<ng2B *ngIf="!destroyIt"></ng2B>', standalone: false, }) class Ng2ComponentA { destroyIt = false; constructor() { ng2ComponentAInstance = this; } } @Component({ selector: 'ng2B', template: '<ng1></ng1>', standalone: false, }) class Ng2ComponentB {} // Define `ng1Module` angular .module_('ng1Module', []) .component('ng1', ng1Component) .directive('ng2A', adapter.downgradeNg2Component(Ng2ComponentA)); // Define `Ng2Module` @NgModule({ declarations: [adapter.upgradeNg1Component('ng1'), Ng2ComponentA, Ng2ComponentB], imports: [BrowserModule], }) class Ng2Module { ngDoBootstrap() {} } // Bootstrap const element = html(`<ng2-a></ng2-a>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { const $rootScope = ref.ng1RootScope as any; tick(); $rootScope.$digest(); (ng1DescendantElement[0] as HTMLElement).click(); expect(elementClickListener).toHaveBeenCalledTimes(1); expect(descendantClickListener).toHaveBeenCalledTimes(1); ng2ComponentAInstance.destroyIt = true; tick(); $rootScope.$digest(); (ng1DescendantElement[0] as HTMLElement).click(); expect(elementClickListener).toHaveBeenCalledTimes(1); expect(descendantClickListener).toHaveBeenCalledTimes(1); }); })); });
{ "end_byte": 95009, "start_byte": 85408, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts" }
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_95017_102267
describe('linking', () => { it('should run the pre-linking after instantiating the controller', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const log: string[] = []; // Define `ng1Directive` const ng1Directive: angular.IDirective = { template: '', link: {pre: () => log.push('ng1-pre')}, controller: class { constructor() { log.push('ng1-ctrl'); } }, }; // Define `Ng2Component` @Component({ selector: 'ng2', template: '<ng1></ng1>', standalone: false, }) class Ng2Component {} // Define `ng1Module` const ng1Module = angular .module_('ng1', []) .directive('ng1', () => ng1Directive) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1']).ready(() => { setTimeout(() => expect(log).toEqual(['ng1-ctrl', 'ng1-pre']), 1000); }); })); it('should run the pre-linking function before linking', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const log: string[] = []; // Define `ng1Directive` const ng1DirectiveA: angular.IDirective = { template: '<ng1-b></ng1-b>', link: {pre: () => log.push('ng1A-pre')}, }; const ng1DirectiveB: angular.IDirective = {link: () => log.push('ng1B-post')}; // Define `Ng2Component` @Component({ selector: 'ng2', template: '<ng1-a></ng1-a>', standalone: false, }) class Ng2Component {} // Define `ng1Module` const ng1Module = angular .module_('ng1', []) .directive('ng1A', () => ng1DirectiveA) .directive('ng1B', () => ng1DirectiveB) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1A'), Ng2Component], schemas: [NO_ERRORS_SCHEMA], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1']).ready(() => { expect(log).toEqual(['ng1A-pre', 'ng1B-post']); }); })); it('should run the post-linking function after linking (link: object)', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const log: string[] = []; // Define `ng1Directive` const ng1DirectiveA: angular.IDirective = { template: '<ng1-b></ng1-b>', link: {post: () => log.push('ng1A-post')}, }; const ng1DirectiveB: angular.IDirective = {link: () => log.push('ng1B-post')}; // Define `Ng2Component` @Component({ selector: 'ng2', template: '<ng1-a></ng1-a>', standalone: false, }) class Ng2Component {} // Define `ng1Module` const ng1Module = angular .module_('ng1', []) .directive('ng1A', () => ng1DirectiveA) .directive('ng1B', () => ng1DirectiveB) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1A'), Ng2Component], schemas: [NO_ERRORS_SCHEMA], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1']).ready(() => { expect(log).toEqual(['ng1B-post', 'ng1A-post']); }); })); it('should run the post-linking function after linking (link: function)', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const log: string[] = []; // Define `ng1Directive` const ng1DirectiveA: angular.IDirective = { template: '<ng1-b></ng1-b>', link: () => log.push('ng1A-post'), }; const ng1DirectiveB: angular.IDirective = {link: () => log.push('ng1B-post')}; // Define `Ng2Component` @Component({ selector: 'ng2', template: '<ng1-a></ng1-a>', standalone: false, }) class Ng2Component {} // Define `ng1Module` const ng1Module = angular .module_('ng1', []) .directive('ng1A', () => ng1DirectiveA) .directive('ng1B', () => ng1DirectiveB) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1A'), Ng2Component], schemas: [NO_ERRORS_SCHEMA], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1']).ready(() => { expect(log).toEqual(['ng1B-post', 'ng1A-post']); }); })); it('should run the post-linking function before `$postLink`', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const log: string[] = []; // Define `ng1Directive` const ng1Directive: angular.IDirective = { template: '', link: () => log.push('ng1-post'), controller: class { $postLink() { log.push('ng1-$post'); } }, }; // Define `Ng2Component` @Component({ selector: 'ng2', template: '<ng1></ng1>', standalone: false, }) class Ng2Component {} // Define `ng1Module` const ng1Module = angular .module_('ng1', []) .directive('ng1', () => ng1Directive) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1']).ready(() => { expect(log).toEqual(['ng1-post', 'ng1-$post']); }); })); });
{ "end_byte": 102267, "start_byte": 95017, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts" }
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_102275_108923
describe('transclusion', () => { it('should support single-slot transclusion', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); let ng2ComponentAInstance: Ng2ComponentA; let ng2ComponentBInstance: Ng2ComponentB; // Define `ng1Component` const ng1Component: angular.IComponent = { template: 'ng1(<div ng-transclude></div>)', transclude: true, }; // Define `Ng2Component` @Component({ selector: 'ng2A', template: 'ng2A(<ng1>{{ value }} | <ng2B *ngIf="showB"></ng2B></ng1>)', standalone: false, }) class Ng2ComponentA { value = 'foo'; showB = false; constructor() { ng2ComponentAInstance = this; } } @Component({ selector: 'ng2B', template: 'ng2B({{ value }})', standalone: false, }) class Ng2ComponentB { value = 'bar'; constructor() { ng2ComponentBInstance = this; } } // Define `ng1Module` const ng1Module = angular .module_('ng1Module', []) .component('ng1', ng1Component) .directive('ng2A', adapter.downgradeNg2Component(Ng2ComponentA)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2ComponentA, Ng2ComponentB], }) class Ng2Module {} // Bootstrap const element = html(`<ng2-a></ng2-a>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { expect(multiTrim(element.textContent)).toBe('ng2A(ng1(foo | ))'); ng2ComponentAInstance.value = 'baz'; ng2ComponentAInstance.showB = true; $digest(ref); expect(multiTrim(element.textContent)).toBe('ng2A(ng1(baz | ng2B(bar)))'); ng2ComponentBInstance.value = 'qux'; $digest(ref); expect(multiTrim(element.textContent)).toBe('ng2A(ng1(baz | ng2B(qux)))'); }); })); it('should support single-slot transclusion with fallback content', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); let ng1ControllerInstances: any[] = []; let ng2ComponentInstance: Ng2Component; // Define `ng1Component` const ng1Component: angular.IComponent = { template: 'ng1(<div ng-transclude>{{ $ctrl.value }}</div>)', transclude: true, controller: class { value = 'from-ng1'; constructor() { ng1ControllerInstances.push(this); } }, }; // Define `Ng2Component` @Component({ selector: 'ng2', template: ` ng2( <ng1 ><div>{{ value }}</div></ng1 > | <!-- Interpolation-only content should still be detected as transcluded content. --> <ng1>{{ value }}</ng1> | <ng1></ng1> )`, standalone: false, }) class Ng2Component { value = 'from-ng2'; constructor() { ng2ComponentInstance = this; } } // Define `ng1Module` const ng1Module = angular .module_('ng1Module', []) .component('ng1', ng1Component) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { expect(multiTrim(element.textContent, true)).toBe( 'ng2(ng1(from-ng2)|ng1(from-ng2)|ng1(from-ng1))', ); ng1ControllerInstances.forEach((ctrl) => (ctrl.value = 'ng1-foo')); ng2ComponentInstance.value = 'ng2-bar'; $digest(ref); expect(multiTrim(element.textContent, true)).toBe( 'ng2(ng1(ng2-bar)|ng1(ng2-bar)|ng1(ng1-foo))', ); }); })); it('should support multi-slot transclusion', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); let ng2ComponentInstance: Ng2Component; // Define `ng1Component` const ng1Component: angular.IComponent = { template: 'ng1(x(<div ng-transclude="slotX"></div>) | y(<div ng-transclude="slotY"></div>))', transclude: {slotX: 'contentX', slotY: 'contentY'}, }; // Define `Ng2Component` @Component({ selector: 'ng2', template: ` ng2( <ng1> <content-x>{{ x }}1</content-x> <content-y>{{ y }}1</content-y> <content-x>{{ x }}2</content-x> <content-y>{{ y }}2</content-y> </ng1> )`, standalone: false, }) class Ng2Component { x = 'foo'; y = 'bar'; constructor() { ng2ComponentInstance = this; } } // Define `ng1Module` const ng1Module = angular .module_('ng1Module', []) .component('ng1', ng1Component) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], schemas: [NO_ERRORS_SCHEMA], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(foo1foo2)|y(bar1bar2)))'); ng2ComponentInstance.x = 'baz'; ng2ComponentInstance.y = 'qux'; $digest(ref); expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz1baz2)|y(qux1qux2)))'); }); }));
{ "end_byte": 108923, "start_byte": 102275, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts" }
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_108933_116093
it('should support default slot (with fallback content)', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); let ng1ControllerInstances: any[] = []; let ng2ComponentInstance: Ng2Component; // Define `ng1Component` const ng1Component: angular.IComponent = { template: 'ng1(default(<div ng-transclude="">fallback-{{ $ctrl.value }}</div>))', transclude: {slotX: 'contentX', slotY: 'contentY'}, controller: class { value = 'ng1'; constructor() { ng1ControllerInstances.push(this); } }, }; // Define `Ng2Component` @Component({ selector: 'ng2', template: ` ng2( <ng1> ({{ x }}) <content-x>ignored x</content-x> {{ x }}-<span>{{ y }}</span> <content-y>ignored y</content-y> <span>({{ y }})</span> </ng1> | <!-- Remove any whitespace, because in AngularJS versions prior to 1.6 even whitespace counts as transcluded content. --> <ng1><content-x>ignored x</content-x><content-y>ignored y</content-y></ng1> | <!-- Interpolation-only content should still be detected as transcluded content. --> <ng1 >{{ x }}<content-x>ignored x</content-x>{{ y + x }}<content-y>ignored y</content-y >{{ y }}</ng1 > )`, standalone: false, }) class Ng2Component { x = 'foo'; y = 'bar'; constructor() { ng2ComponentInstance = this; } } // Define `ng1Module` const ng1Module = angular .module_('ng1Module', []) .component('ng1', ng1Component) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], schemas: [NO_ERRORS_SCHEMA], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { expect(multiTrim(element.textContent, true)).toBe( 'ng2(ng1(default((foo)foo-bar(bar)))|ng1(default(fallback-ng1))|ng1(default(foobarfoobar)))', ); ng1ControllerInstances.forEach((ctrl) => (ctrl.value = 'ng1-plus')); ng2ComponentInstance.x = 'baz'; ng2ComponentInstance.y = 'qux'; $digest(ref); expect(multiTrim(element.textContent, true)).toBe( 'ng2(ng1(default((baz)baz-qux(qux)))|ng1(default(fallback-ng1-plus))|ng1(default(bazquxbazqux)))', ); }); })); it('should support optional transclusion slots (with fallback content)', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); let ng1ControllerInstances: any[] = []; let ng2ComponentInstance: Ng2Component; // Define `ng1Component` const ng1Component: angular.IComponent = { template: ` ng1( x(<div ng-transclude="slotX">{{ $ctrl.x }}</div>) | y(<div ng-transclude="slotY">{{ $ctrl.y }}</div>) )`, transclude: {slotX: '?contentX', slotY: '?contentY'}, controller: class { x = 'ng1X'; y = 'ng1Y'; constructor() { ng1ControllerInstances.push(this); } }, }; // Define `Ng2Component` @Component({ selector: 'ng2', template: ` ng2( <ng1 ><content-x>{{ x }}</content-x></ng1 > | <ng1 ><content-y>{{ y }}</content-y></ng1 > )`, standalone: false, }) class Ng2Component { x = 'ng2X'; y = 'ng2Y'; constructor() { ng2ComponentInstance = this; } } // Define `ng1Module` const ng1Module = angular .module_('ng1Module', []) .component('ng1', ng1Component) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], schemas: [NO_ERRORS_SCHEMA], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { expect(multiTrim(element.textContent, true)).toBe( 'ng2(ng1(x(ng2X)|y(ng1Y))|ng1(x(ng1X)|y(ng2Y)))', ); ng1ControllerInstances.forEach((ctrl) => { ctrl.x = 'ng1X-foo'; ctrl.y = 'ng1Y-bar'; }); ng2ComponentInstance.x = 'ng2X-baz'; ng2ComponentInstance.y = 'ng2Y-qux'; $digest(ref); expect(multiTrim(element.textContent, true)).toBe( 'ng2(ng1(x(ng2X-baz)|y(ng1Y-bar))|ng1(x(ng1X-foo)|y(ng2Y-qux)))', ); }); })); it('should throw if a non-optional slot is not filled', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); let errorMessage: string; // Define `ng1Component` const ng1Component: angular.IComponent = { template: '', transclude: {slotX: '?contentX', slotY: 'contentY'}, }; // Define `Ng2Component` @Component({ selector: 'ng2', template: '<ng1></ng1>', standalone: false, }) class Ng2Component {} // Define `ng1Module` const ng1Module = angular .module_('ng1Module', []) .value($EXCEPTION_HANDLER, (error: Error) => (errorMessage = error.message)) .component('ng1', ng1Component) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { expect(errorMessage).toContain("Required transclusion slot 'slotY' on directive: ng1"); }); }));
{ "end_byte": 116093, "start_byte": 108933, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts" }
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_116103_123596
it('should support structural directives in transcluded content', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); let ng2ComponentInstance: Ng2Component; // Define `ng1Component` const ng1Component: angular.IComponent = { template: 'ng1(x(<div ng-transclude="slotX"></div>) | default(<div ng-transclude=""></div>))', transclude: {slotX: 'contentX'}, }; // Define `Ng2Component` @Component({ selector: 'ng2', template: ` ng2( <ng1> <content-x ><div *ngIf="show">{{ x }}1</div></content-x > <div *ngIf="!show">{{ y }}1</div> <content-x ><div *ngIf="!show">{{ x }}2</div></content-x > <div *ngIf="show">{{ y }}2</div> </ng1> )`, standalone: false, }) class Ng2Component { x = 'foo'; y = 'bar'; show = true; constructor() { ng2ComponentInstance = this; } } // Define `ng1Module` const ng1Module = angular .module_('ng1Module', []) .component('ng1', ng1Component) .directive('ng2', adapter.downgradeNg2Component(Ng2Component)); // Define `Ng2Module` @NgModule({ imports: [BrowserModule], declarations: [adapter.upgradeNg1Component('ng1'), Ng2Component], schemas: [NO_ERRORS_SCHEMA], }) class Ng2Module {} // Bootstrap const element = html(`<ng2></ng2>`); adapter.bootstrap(element, ['ng1Module']).ready((ref) => { expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(foo1)|default(bar2)))'); ng2ComponentInstance.x = 'baz'; ng2ComponentInstance.y = 'qux'; ng2ComponentInstance.show = false; $digest(ref); expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz2)|default(qux1)))'); ng2ComponentInstance.show = true; $digest(ref); expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz1)|default(qux2)))'); }); })); }); it('should bind input properties (<) of components', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const ng1Module = angular.module_('ng1', []); const ng1 = { bindings: {personProfile: '<'}, template: 'Hello {{$ctrl.personProfile.firstName}} {{$ctrl.personProfile.lastName}}', controller: class {}, }; ng1Module.component('ng1', ng1); @Component({ selector: 'ng2', template: '<ng1 [personProfile]="goku"></ng1>', standalone: false, }) class Ng2 { goku = {firstName: 'GOKU', lastName: 'SAN'}; } @NgModule({ declarations: [adapter.upgradeNg1Component('ng1'), Ng2], imports: [BrowserModule], }) class Ng2Module {} ng1Module.directive('ng2', adapter.downgradeNg2Component(Ng2)); const element = html(`<div><ng2></ng2></div>`); adapter.bootstrap(element, ['ng1']).ready((ref) => { expect(multiTrim(document.body.textContent)).toEqual(`Hello GOKU SAN`); ref.dispose(); }); })); it('should support ng2 > ng1 > ng2', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const ng1Module = angular.module_('ng1', []); const ng1 = { template: 'ng1(<ng2b></ng2b>)', }; ng1Module.component('ng1', ng1); @Component({ selector: 'ng2a', template: 'ng2a(<ng1></ng1>)', standalone: false, }) class Ng2a {} ng1Module.directive('ng2a', adapter.downgradeNg2Component(Ng2a)); @Component({ selector: 'ng2b', template: 'ng2b', standalone: false, }) class Ng2b {} ng1Module.directive('ng2b', adapter.downgradeNg2Component(Ng2b)); @NgModule({ declarations: [adapter.upgradeNg1Component('ng1'), Ng2a, Ng2b], imports: [BrowserModule], }) class Ng2Module {} const element = html(`<div><ng2a></ng2a></div>`); adapter.bootstrap(element, ['ng1']).ready((ref) => { expect(multiTrim(document.body.textContent)).toEqual('ng2a(ng1(ng2b))'); }); })); }); describe('injection', () => { function SomeToken() {} it('should export ng2 instance to ng1', waitForAsync(() => { @NgModule({ providers: [{provide: SomeToken, useValue: 'correct_value'}], imports: [BrowserModule], }) class MyNg2Module {} const adapter: UpgradeAdapter = new UpgradeAdapter(MyNg2Module); const module = angular.module_('myExample', []); module.factory('someToken', adapter.downgradeNg2Provider(SomeToken)); adapter.bootstrap(html('<div>'), ['myExample']).ready((ref) => { expect(ref.ng1Injector.get('someToken')).toBe('correct_value'); ref.dispose(); }); })); it('should export ng1 instance to ng2', waitForAsync(() => { @NgModule({imports: [BrowserModule]}) class MyNg2Module {} const adapter: UpgradeAdapter = new UpgradeAdapter(MyNg2Module); const module = angular.module_('myExample', []); module.value('testValue', 'secreteToken'); adapter.upgradeNg1Provider('testValue'); adapter.upgradeNg1Provider('testValue', {asToken: 'testToken'}); adapter.upgradeNg1Provider('testValue', {asToken: String}); adapter.bootstrap(html('<div>'), ['myExample']).ready((ref) => { expect(ref.ng2Injector.get('testValue')).toBe('secreteToken'); expect(ref.ng2Injector.get(String)).toBe('secreteToken'); expect(ref.ng2Injector.get('testToken')).toBe('secreteToken'); ref.dispose(); }); })); it('should respect hierarchical dependency injection for ng2', waitForAsync(() => { const ng1Module = angular.module_('ng1', []); @Component({ selector: 'ng2-parent', template: `ng2-parent(<ng-content></ng-content>)`, standalone: false, }) class Ng2Parent {} @Component({ selector: 'ng2-child', template: `ng2-child`, standalone: false, }) class Ng2Child { constructor(parent: Ng2Parent) {} } @NgModule({declarations: [Ng2Parent, Ng2Child], imports: [BrowserModule]}) class Ng2Module {} const element = html('<ng2-parent><ng2-child></ng2-child></ng2-parent>'); const adapter: UpgradeAdapter = new UpgradeAdapter(Ng2Module); ng1Module .directive('ng2Parent', adapter.downgradeNg2Component(Ng2Parent)) .directive('ng2Child', adapter.downgradeNg2Component(Ng2Child)); adapter.bootstrap(element, ['ng1']).ready((ref) => { expect(document.body.textContent).toEqual('ng2-parent(ng2-child)'); ref.dispose(); }); })); });
{ "end_byte": 123596, "start_byte": 116103, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts" }
angular/packages/upgrade/src/dynamic/test/upgrade_spec.ts_123602_128892
describe('testability', () => { it('should handle deferred bootstrap', waitForAsync(() => { @NgModule({imports: [BrowserModule]}) class MyNg2Module {} const adapter: UpgradeAdapter = new UpgradeAdapter(MyNg2Module); angular.module_('ng1', []); let bootstrapResumed: boolean = false; const element = html('<div></div>'); window.name = 'NG_DEFER_BOOTSTRAP!' + window.name; adapter.bootstrap(element, ['ng1']).ready((ref) => { expect(bootstrapResumed).toEqual(true); ref.dispose(); }); setTimeout(() => { bootstrapResumed = true; (<any>window).angular.resumeBootstrap(); }, 100); })); it('should propagate return value of resumeBootstrap', fakeAsync(() => { @NgModule({imports: [BrowserModule]}) class MyNg2Module {} const adapter: UpgradeAdapter = new UpgradeAdapter(MyNg2Module); const ng1Module = angular.module_('ng1', []); let a1Injector: angular.IInjectorService | undefined; ng1Module.run([ '$injector', function ($injector: angular.IInjectorService) { a1Injector = $injector; }, ]); const element = html('<div></div>'); window.name = 'NG_DEFER_BOOTSTRAP!' + window.name; adapter.bootstrap(element, [ng1Module.name]).ready((ref) => { ref.dispose(); }); tick(100); const value = (<any>window).angular.resumeBootstrap(); expect(value).toBe(a1Injector); })); it('should wait for ng2 testability', waitForAsync(() => { @NgModule({imports: [BrowserModule]}) class MyNg2Module {} const adapter: UpgradeAdapter = new UpgradeAdapter(MyNg2Module); angular.module_('ng1', []); const element = html('<div></div>'); adapter.bootstrap(element, ['ng1']).ready((ref) => { const zone = ref.ng2Injector.get(NgZone); let ng2Stable = false; zone.run(() => { setTimeout(() => { ng2Stable = true; }, 100); }); angular.getTestability(element).whenStable(() => { expect(ng2Stable).toEqual(true); ref.dispose(); }); }); })); }); describe('examples', () => { it('should verify UpgradeAdapter example', waitForAsync(() => { const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module)); const module = angular.module_('myExample', []); const ng1 = () => { return { scope: {title: '='}, transclude: true, template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)', }; }; module.directive('ng1', ng1); @Component({ selector: 'ng2', inputs: ['name'], template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)', standalone: false, }) class Ng2 {} @NgModule({ declarations: [adapter.upgradeNg1Component('ng1'), Ng2], imports: [BrowserModule], }) class Ng2Module {} module.directive('ng2', adapter.downgradeNg2Component(Ng2)); document.body.innerHTML = '<ng2 name="World">project</ng2>'; adapter.bootstrap(document.body.firstElementChild!, ['myExample']).ready((ref) => { expect(multiTrim(document.body.textContent)).toEqual( 'ng2[ng1[Hello World!](transclude)](project)', ); ref.dispose(); }); })); }); describe('registerForNg1Tests', () => { let upgradeAdapterRef: UpgradeAdapterRef; let $compile: angular.ICompileService; let $rootScope: angular.IRootScopeService; beforeEach(() => { const ng1Module = angular.module_('ng1', []); @Component({ selector: 'ng2', template: 'Hello World', standalone: false, }) class Ng2 {} @NgModule({declarations: [Ng2], imports: [BrowserModule]}) class Ng2Module {} const upgradeAdapter = new UpgradeAdapter(Ng2Module); ng1Module.directive('ng2', upgradeAdapter.downgradeNg2Component(Ng2)); upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['ng1']); }); beforeEach(() => { inject((_$compile_: angular.ICompileService, _$rootScope_: angular.IRootScopeService) => { $compile = _$compile_; $rootScope = _$rootScope_; }); }); it('should be able to test ng1 components that use ng2 components', waitForAsync(() => { upgradeAdapterRef.ready(() => { const element = $compile('<ng2></ng2>')($rootScope); $rootScope.$digest(); expect(element[0].textContent).toContain('Hello World'); }); })); }); }); }); function $apply(adapter: UpgradeAdapterRef, exp: angular.Ng1Expression) { const $rootScope = adapter.ng1Injector.get($ROOT_SCOPE) as angular.IRootScopeService; $rootScope.$apply(exp); } function $digest(adapter: UpgradeAdapterRef) { const $rootScope = adapter.ng1Injector.get($ROOT_SCOPE) as angular.IRootScopeService; $rootScope.$digest(); }
{ "end_byte": 128892, "start_byte": 123602, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/upgrade_spec.ts" }
angular/packages/upgrade/src/dynamic/test/BUILD.bazel_0_609
load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages/core", "//packages/core/testing", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/upgrade", "//packages/upgrade/src/common", "//packages/upgrade/src/common/test/helpers", ], ) karma_web_test_suite( name = "test", static_files = [ "//:angularjs_scripts", ], deps = [ ":test_lib", ], )
{ "end_byte": 609, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/test/BUILD.bazel" }
angular/packages/upgrade/src/dynamic/src/upgrade_adapter.ts_0_4774
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Compiler, CompilerOptions, Injector, NgModule, NgModuleRef, NgZone, resolveForwardRef, StaticProvider, Testability, Type, } from '@angular/core'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import { bootstrap, element as angularElement, IAngularBootstrapConfig, IAugmentedJQuery, IInjectorService, IModule, IProvideService, IRootScopeService, ITestabilityService, module_ as angularModule, } from '../../common/src/angular1'; import { $$TESTABILITY, $COMPILE, $INJECTOR, $ROOT_SCOPE, COMPILER_KEY, INJECTOR_KEY, LAZY_MODULE_REF, NG_ZONE_KEY, UPGRADE_APP_TYPE_KEY, } from '../../common/src/constants'; import {downgradeComponent} from '../../common/src/downgrade_component'; import {downgradeInjectable} from '../../common/src/downgrade_injectable'; import { controllerKey, Deferred, destroyApp, LazyModuleRef, onError, UpgradeAppType, } from '../../common/src/util'; import {UpgradeNg1ComponentAdapterBuilder} from './upgrade_ng1_adapter'; let upgradeCount: number = 0; /** * Use `UpgradeAdapter` to allow AngularJS and Angular to coexist in a single application. * * The `UpgradeAdapter` allows: * 1. creation of Angular component from AngularJS component directive * (See {@link UpgradeAdapter#upgradeNg1Component}) * 2. creation of AngularJS directive from Angular component. * (See {@link UpgradeAdapter#downgradeNg2Component}) * 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks * coexisting in a single application. * * @usageNotes * ### Mental Model * * When reasoning about how a hybrid application works it is useful to have a mental model which * describes what is happening and explains what is happening at the lowest level. * * 1. There are two independent frameworks running in a single application, each framework treats * the other as a black box. * 2. Each DOM element on the page is owned exactly by one framework. Whichever framework * instantiated the element is the owner. Each framework only updates/interacts with its own * DOM elements and ignores others. * 3. AngularJS directives always execute inside AngularJS framework codebase regardless of * where they are instantiated. * 4. Angular components always execute inside Angular framework codebase regardless of * where they are instantiated. * 5. An AngularJS component can be upgraded to an Angular component. This creates an * Angular directive, which bootstraps the AngularJS component directive in that location. * 6. An Angular component can be downgraded to an AngularJS component directive. This creates * an AngularJS directive, which bootstraps the Angular component in that location. * 7. Whenever an adapter component is instantiated the host element is owned by the framework * doing the instantiation. The other framework then instantiates and owns the view for that * component. This implies that component bindings will always follow the semantics of the * instantiation framework. The syntax is always that of Angular syntax. * 8. AngularJS is always bootstrapped first and owns the bottom most view. * 9. The new application is running in Angular zone, and therefore it no longer needs calls to * `$apply()`. * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions); * const module = angular.module('myExample', []); * module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component)); * * module.directive('ng1Hello', function() { * return { * scope: { title: '=' }, * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' * }; * }); * * * @Component({ * selector: 'ng2-comp', * inputs: ['name'], * template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)', * directives: * }) * class Ng2Component { * } * * @NgModule({ * declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * * document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual( * "ng2[ng1[Hello World!](transclude)](project)"); * }); * * ``` * * @deprecated Deprecated since v5. Use `upgrade/static` instead, which also supports * [Ahead-of-Time compilation](tools/cli/aot-compiler). * @publicApi */
{ "end_byte": 4774, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/src/upgrade_adapter.ts" }
angular/packages/upgrade/src/dynamic/src/upgrade_adapter.ts_4775_12493
export class UpgradeAdapter { private idPrefix: string = `NG2_UPGRADE_${upgradeCount++}_`; private downgradedComponents: Type<any>[] = []; /** * An internal map of ng1 components which need to up upgraded to ng2. * * We can't upgrade until injector is instantiated and we can retrieve the component metadata. * For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped. * * @internal */ private ng1ComponentsToBeUpgraded: {[name: string]: UpgradeNg1ComponentAdapterBuilder} = {}; private upgradedProviders: StaticProvider[] = []; private moduleRef: NgModuleRef<any> | null = null; constructor( private ng2AppModule: Type<any>, private compilerOptions?: CompilerOptions, ) { if (!ng2AppModule) { throw new Error( 'UpgradeAdapter cannot be instantiated without an NgModule of the Angular app.', ); } } /** * Allows Angular Component to be used from AngularJS. * * Use `downgradeNg2Component` to create an AngularJS Directive Definition Factory from * Angular Component. The adapter will bootstrap Angular component from within the * AngularJS template. * * @usageNotes * ### Mental Model * * 1. The component is instantiated by being listed in AngularJS template. This means that the * host element is controlled by AngularJS, but the component's view will be controlled by * Angular. * 2. Even thought the component is instantiated in AngularJS, it will be using Angular * syntax. This has to be done, this way because we must follow Angular components do not * declare how the attributes should be interpreted. * 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component * by way of the `ControlValueAccessor` interface from @angular/forms. Only components that * implement this interface are eligible. * * ### Supported Features * * - Bindings: * - Attribute: `<comp name="World">` * - Interpolation: `<comp greeting="Hello {{name}}!">` * - Expression: `<comp [name]="username">` * - Event: `<comp (close)="doSomething()">` * - ng-model: `<comp ng-model="name">` * - Content projection: yes * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); * const module = angular.module('myExample', []); * module.directive('greet', adapter.downgradeNg2Component(Greeter)); * * @Component({ * selector: 'greet', * template: '{{salutation}} {{name}}! - <ng-content></ng-content>' * }) * class Greeter { * @Input() salutation: string; * @Input() name: string; * } * * @NgModule({ * declarations: [Greeter], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = * 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual("ng1 template: Hello world! - text"); * }); * ``` */ downgradeNg2Component(component: Type<any>): Function { this.downgradedComponents.push(component); return downgradeComponent({component}); } /** * Allows AngularJS Component to be used from Angular. * * Use `upgradeNg1Component` to create an Angular component from AngularJS Component * directive. The adapter will bootstrap AngularJS component from within the Angular * template. * * @usageNotes * ### Mental Model * * 1. The component is instantiated by being listed in Angular template. This means that the * host element is controlled by Angular, but the component's view will be controlled by * AngularJS. * * ### Supported Features * * - Bindings: * - Attribute: `<comp name="World">` * - Interpolation: `<comp greeting="Hello {{name}}!">` * - Expression: `<comp [name]="username">` * - Event: `<comp (close)="doSomething()">` * - Transclusion: yes * - Only some of the features of * [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are * supported: * - `compile`: not supported because the host element is owned by Angular, which does * not allow modifying DOM structure during compilation. * - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.) * - `controllerAs`: supported. * - `bindToController`: supported. * - `link`: supported. (NOTE: only pre-link function is supported.) * - `name`: supported. * - `priority`: ignored. * - `replace`: not supported. * - `require`: supported. * - `restrict`: must be set to 'E'. * - `scope`: supported. * - `template`: supported. * - `templateUrl`: supported. * - `terminal`: ignored. * - `transclude`: supported. * * * ### Example * * ``` * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); * const module = angular.module('myExample', []); * * module.directive('greet', function() { * return { * scope: {salutation: '=', name: '=' }, * template: '{{salutation}} {{name}}! - <span ng-transclude></span>' * }; * }); * * module.directive('ng2', adapter.downgradeNg2Component(Ng2Component)); * * @Component({ * selector: 'ng2', * template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>' * }) * class Ng2Component { * } * * @NgModule({ * declarations: [Ng2Component, adapter.upgradeNg1Component('greet')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = '<ng2></ng2>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual("ng2 template: Hello world! - text"); * }); * ``` */ upgradeNg1Component(name: string): Type<any> { if (this.ng1ComponentsToBeUpgraded.hasOwnProperty(name)) { return this.ng1ComponentsToBeUpgraded[name].type; } else { return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name)) .type; } } /** * Registers the adapter's AngularJS upgrade module for unit testing in AngularJS. * Use this instead of `angular.mock.module()` to load the upgrade module into * the AngularJS testing injector. * * @usageNotes * ### Example * * ``` * const upgradeAdapter = new UpgradeAdapter(MyNg2Module); * * // configure the adapter with upgrade/downgrade components and services * upgradeAdapter.downgradeNg2Component(MyComponent); * * let upgradeAdapterRef: UpgradeAdapterRef; * let $compile, $rootScope; * * // We must register the adapter before any calls to `inject()` * beforeEach(() => { * upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']); * }); * * beforeEach(inject((_$compile_, _$rootScope_) => { * $compile = _$compile_; * $rootScope = _$rootScope_; * })); * * it("says hello", (done) => { * upgradeAdapterRef.ready(() => { * const element = $compile("<my-component></my-component>")($rootScope); * $rootScope.$apply(); * expect(element.html()).toContain("Hello World"); * done(); * }) * }); * * ``` * * @param modules any AngularJS modules that the upgrade module should depend upon * @returns an `UpgradeAdapterRef`, which lets you register a `ready()` callback to * run assertions once the Angular components are ready to test through AngularJS. */
{ "end_byte": 12493, "start_byte": 4775, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/src/upgrade_adapter.ts" }
angular/packages/upgrade/src/dynamic/src/upgrade_adapter.ts_12496_18039
registerForNg1Tests(modules?: string[]): UpgradeAdapterRef { const windowNgMock = (window as any)['angular'].mock; if (!windowNgMock || !windowNgMock.module) { throw new Error("Failed to find 'angular.mock.module'."); } const {ng1Module, ng2BootstrapDeferred} = this.declareNg1Module(modules); windowNgMock.module(ng1Module.name); const upgrade = new UpgradeAdapterRef(); ng2BootstrapDeferred.promise.then((ng1Injector) => { // @ts-expect-error upgrade._bootstrapDone(this.moduleRef!, ng1Injector); }, onError); return upgrade; } /** * Bootstrap a hybrid AngularJS / Angular application. * * This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS * [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike * AngularJS, this bootstrap is asynchronous. * * @usageNotes * ### Example * * ``` * const adapter = new UpgradeAdapter(MyNg2Module); * const module = angular.module('myExample', []); * module.directive('ng2', adapter.downgradeNg2Component(Ng2)); * * module.directive('ng1', function() { * return { * scope: { title: '=' }, * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' * }; * }); * * * @Component({ * selector: 'ng2', * inputs: ['name'], * template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)' * }) * class Ng2 { * } * * @NgModule({ * declarations: [Ng2, adapter.upgradeNg1Component('ng1')], * imports: [BrowserModule] * }) * class MyNg2Module {} * * document.body.innerHTML = '<ng2 name="World">project</ng2>'; * * adapter.bootstrap(document.body, ['myExample']).ready(function() { * expect(document.body.textContent).toEqual( * "ng2[ng1[Hello World!](transclude)](project)"); * }); * ``` */ bootstrap( element: Element, modules?: any[], config?: IAngularBootstrapConfig, ): UpgradeAdapterRef { const {ng1Module, ng2BootstrapDeferred, ngZone} = this.declareNg1Module(modules); const upgrade = new UpgradeAdapterRef(); // Make sure resumeBootstrap() only exists if the current bootstrap is deferred const windowAngular = (window as any)['angular']; windowAngular.resumeBootstrap = undefined; ngZone.run(() => { bootstrap(element, [ng1Module.name], config!); }); const ng1BootstrapPromise = new Promise<void>((resolve) => { if (windowAngular.resumeBootstrap) { const originalResumeBootstrap: () => void = windowAngular.resumeBootstrap; windowAngular.resumeBootstrap = function () { windowAngular.resumeBootstrap = originalResumeBootstrap; const r = windowAngular.resumeBootstrap.apply(this, arguments); resolve(); return r; }; } else { resolve(); } }); Promise.all([ng2BootstrapDeferred.promise, ng1BootstrapPromise]).then(([ng1Injector]) => { angularElement(element).data!(controllerKey(INJECTOR_KEY), this.moduleRef!.injector); this.moduleRef!.injector.get<NgZone>(NgZone).run(() => { // @ts-expect-error upgrade._bootstrapDone(this.moduleRef, ng1Injector); }); }, onError); return upgrade; } /** * Allows AngularJS service to be accessible from Angular. * * @usageNotes * ### Example * * ``` * class Login { ... } * class Server { ... } * * @Injectable() * class Example { * constructor(@Inject('server') server, login: Login) { * ... * } * } * * const module = angular.module('myExample', []); * module.service('server', Server); * module.service('login', Login); * * const adapter = new UpgradeAdapter(MyNg2Module); * adapter.upgradeNg1Provider('server'); * adapter.upgradeNg1Provider('login', {asToken: Login}); * * adapter.bootstrap(document.body, ['myExample']).ready((ref) => { * const example: Example = ref.ng2Injector.get(Example); * }); * * ``` */ upgradeNg1Provider(name: string, options?: {asToken: any}) { const token = (options && options.asToken) || name; this.upgradedProviders.push({ provide: token, useFactory: ($injector: IInjectorService) => $injector.get(name), deps: [$INJECTOR], }); } /** * Allows Angular service to be accessible from AngularJS. * * @usageNotes * ### Example * * ``` * class Example { * } * * const adapter = new UpgradeAdapter(MyNg2Module); * * const module = angular.module('myExample', []); * module.factory('example', adapter.downgradeNg2Provider(Example)); * * adapter.bootstrap(document.body, ['myExample']).ready((ref) => { * const example: Example = ref.ng1Injector.get('example'); * }); * * ``` */ downgradeNg2Provider(token: any): Function { return downgradeInjectable(token); } /** * Declare the AngularJS upgrade module for this adapter without bootstrapping the whole * hybrid application. * * This method is automatically called by `bootstrap()` and `registerForNg1Tests()`. * * @param modules The AngularJS modules that this upgrade module should depend upon. * @returns The AngularJS upgrade module that is declared by this method * * @usageNotes * ### Example * * ``` * const upgradeAdapter = new UpgradeAdapter(MyNg2Module); * upgradeAdapter.declareNg1Module(['heroApp']); * ``` */
{ "end_byte": 18039, "start_byte": 12496, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/src/upgrade_adapter.ts" }
angular/packages/upgrade/src/dynamic/src/upgrade_adapter.ts_18042_25473
private declareNg1Module(modules: string[] = []): { ng1Module: IModule; ng2BootstrapDeferred: Deferred<IInjectorService>; ngZone: NgZone; } { const delayApplyExps: Function[] = []; let original$applyFn: Function; let rootScopePrototype: any; const upgradeAdapter = this; const ng1Module = angularModule(this.idPrefix, modules); const platformRef = platformBrowserDynamic(); const ngZone = new NgZone({ enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec'), }); const ng2BootstrapDeferred = new Deferred<IInjectorService>(); ng1Module .constant(UPGRADE_APP_TYPE_KEY, UpgradeAppType.Dynamic) .factory(INJECTOR_KEY, () => this.moduleRef!.injector.get(Injector)) .factory(LAZY_MODULE_REF, [ INJECTOR_KEY, (injector: Injector) => ({injector}) as LazyModuleRef, ]) .constant(NG_ZONE_KEY, ngZone) .factory(COMPILER_KEY, () => this.moduleRef!.injector.get(Compiler)) .config([ '$provide', '$injector', (provide: IProvideService, ng1Injector: IInjectorService) => { provide.decorator($ROOT_SCOPE, [ '$delegate', function (rootScopeDelegate: IRootScopeService) { // Capture the root apply so that we can delay first call to $apply until we // bootstrap Angular and then we replay and restore the $apply. rootScopePrototype = rootScopeDelegate.constructor.prototype; if (rootScopePrototype.hasOwnProperty('$apply')) { original$applyFn = rootScopePrototype.$apply; rootScopePrototype.$apply = (exp: any) => delayApplyExps.push(exp); } else { throw new Error("Failed to find '$apply' on '$rootScope'!"); } return rootScopeDelegate; }, ]); if (ng1Injector.has($$TESTABILITY)) { provide.decorator($$TESTABILITY, [ '$delegate', function (testabilityDelegate: ITestabilityService) { const originalWhenStable: Function = testabilityDelegate.whenStable; // Cannot use arrow function below because we need the context const newWhenStable = function (this: unknown, callback: Function) { originalWhenStable.call(this, function (this: unknown) { const ng2Testability: Testability = upgradeAdapter.moduleRef!.injector.get(Testability); if (ng2Testability.isStable()) { callback.apply(this, arguments); } else { ng2Testability.whenStable(newWhenStable.bind(this, callback)); } }); }; testabilityDelegate.whenStable = newWhenStable; return testabilityDelegate; }, ]); } }, ]); ng1Module.run([ '$injector', '$rootScope', (ng1Injector: IInjectorService, rootScope: IRootScopeService) => { UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, ng1Injector) .then(() => { // At this point we have ng1 injector and we have prepared // ng1 components to be upgraded, we now can bootstrap ng2. @NgModule({ jit: true, providers: [ {provide: $INJECTOR, useFactory: () => ng1Injector}, {provide: $COMPILE, useFactory: () => ng1Injector.get($COMPILE)}, this.upgradedProviders, ], imports: [resolveForwardRef(this.ng2AppModule)], }) class DynamicNgUpgradeModule { ngDoBootstrap() {} } platformRef .bootstrapModule(DynamicNgUpgradeModule, [this.compilerOptions!, {ngZone}]) .then((ref: NgModuleRef<any>) => { this.moduleRef = ref; ngZone.run(() => { if (rootScopePrototype) { rootScopePrototype.$apply = original$applyFn; // restore original $apply while (delayApplyExps.length) { rootScope.$apply(delayApplyExps.shift()); } rootScopePrototype = null; } }); }) .then(() => ng2BootstrapDeferred.resolve(ng1Injector), onError) .then(() => { let subscription = ngZone.onMicrotaskEmpty.subscribe({ next: () => { if (rootScope.$$phase) { if (typeof ngDevMode === 'undefined' || ngDevMode) { console.warn( 'A digest was triggered while one was already in progress. This may mean that something is triggering digests outside the Angular zone.', ); } return rootScope.$evalAsync(() => {}); } return rootScope.$digest(); }, }); rootScope.$on('$destroy', () => { subscription.unsubscribe(); }); // Destroy the AngularJS app once the Angular `PlatformRef` is destroyed. // This does not happen in a typical SPA scenario, but it might be useful for // other use-cases where disposing of an Angular/AngularJS app is necessary // (such as Hot Module Replacement (HMR)). // See https://github.com/angular/angular/issues/39935. platformRef.onDestroy(() => destroyApp(ng1Injector)); }); }) .catch((e) => ng2BootstrapDeferred.reject(e)); }, ]); return {ng1Module, ng2BootstrapDeferred, ngZone}; } } /** * Use `UpgradeAdapterRef` to control a hybrid AngularJS / Angular application. * * @deprecated Deprecated since v5. Use `upgrade/static` instead, which also supports * [Ahead-of-Time compilation](tools/cli/aot-compiler). * @publicApi */ export class UpgradeAdapterRef { /* @internal */ private _readyFn: ((upgradeAdapterRef: UpgradeAdapterRef) => void) | null = null; public ng1RootScope: IRootScopeService = null!; public ng1Injector: IInjectorService = null!; public ng2ModuleRef: NgModuleRef<any> = null!; public ng2Injector: Injector = null!; /* @internal */ private _bootstrapDone(ngModuleRef: NgModuleRef<any>, ng1Injector: IInjectorService) { this.ng2ModuleRef = ngModuleRef; this.ng2Injector = ngModuleRef.injector; this.ng1Injector = ng1Injector; this.ng1RootScope = ng1Injector.get($ROOT_SCOPE); this._readyFn && this._readyFn(this); } /** * Register a callback function which is notified upon successful hybrid AngularJS / Angular * application has been bootstrapped. * * The `ready` callback function is invoked inside the Angular zone, therefore it does not * require a call to `$apply()`. */ public ready(fn: (upgradeAdapterRef: UpgradeAdapterRef) => void) { this._readyFn = fn; } /** * Dispose of running hybrid AngularJS / Angular application. */ public dispose() { this.ng1Injector!.get($ROOT_SCOPE).$destroy(); this.ng2ModuleRef!.destroy(); } }
{ "end_byte": 25473, "start_byte": 18042, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/src/upgrade_adapter.ts" }
angular/packages/upgrade/src/dynamic/src/upgrade_ng1_adapter.ts_0_5272
/** * @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 { Directive, DoCheck, ElementRef, EventEmitter, Inject, Injector, OnChanges, OnDestroy, OnInit, SimpleChange, SimpleChanges, Type, } from '@angular/core'; import { IAttributes, IDirective, IInjectorService, ILinkFn, IScope, ITranscludeFunction, } from '../../common/src/angular1'; import {$SCOPE} from '../../common/src/constants'; import { IBindingDestination, IControllerInstance, UpgradeHelper, } from '../../common/src/upgrade_helper'; import {isFunction, strictEquals} from '../../common/src/util'; import {trustedHTMLFromLegacyTemplate} from '../../common/src/security/trusted_types'; const CAMEL_CASE = /([A-Z])/g; const INITIAL_VALUE = { __UNINITIALIZED__: true, }; const NOT_SUPPORTED: any = 'NOT_SUPPORTED'; function getInputPropertyMapName(name: string): string { return `input_${name}`; } function getOutputPropertyMapName(name: string): string { return `output_${name}`; } export class UpgradeNg1ComponentAdapterBuilder { type: Type<any>; inputs: string[] = []; inputsRename: string[] = []; outputs: string[] = []; outputsRename: string[] = []; propertyOutputs: string[] = []; checkProperties: string[] = []; propertyMap: {[name: string]: string} = {}; directive: IDirective | null = null; template!: string; constructor(public name: string) { const selector = name.replace( CAMEL_CASE, (all: string, next: string) => '-' + next.toLowerCase(), ); const self = this; @Directive({ jit: true, selector: selector, inputs: this.inputsRename, outputs: this.outputsRename, standalone: false, }) class MyClass extends UpgradeNg1ComponentAdapter implements OnInit, OnChanges, DoCheck, OnDestroy { constructor(@Inject($SCOPE) scope: IScope, injector: Injector, elementRef: ElementRef) { super( new UpgradeHelper(injector, name, elementRef, self.directive || undefined), scope, self.template, self.inputs, self.outputs, self.propertyOutputs, self.checkProperties, self.propertyMap, ) as any; } } this.type = MyClass; } extractBindings() { const btcIsObject = typeof this.directive!.bindToController === 'object'; if (btcIsObject && Object.keys(this.directive!.scope!).length) { throw new Error( `Binding definitions on scope and controller at the same time are not supported.`, ); } const context = btcIsObject ? this.directive!.bindToController : this.directive!.scope; if (typeof context == 'object') { Object.keys(context).forEach((propName) => { const definition = context[propName]; const bindingType = definition.charAt(0); const bindingOptions = definition.charAt(1); const attrName = definition.substring(bindingOptions === '?' ? 2 : 1) || propName; // QUESTION: What about `=*`? Ignore? Throw? Support? const inputName = getInputPropertyMapName(attrName); const inputNameRename = `${inputName}: ${attrName}`; const outputName = getOutputPropertyMapName(attrName); const outputNameRename = `${outputName}: ${attrName}`; const outputNameRenameChange = `${outputNameRename}Change`; switch (bindingType) { case '@': case '<': this.inputs.push(inputName); this.inputsRename.push(inputNameRename); this.propertyMap[inputName] = propName; break; case '=': this.inputs.push(inputName); this.inputsRename.push(inputNameRename); this.propertyMap[inputName] = propName; this.outputs.push(outputName); this.outputsRename.push(outputNameRenameChange); this.propertyMap[outputName] = propName; this.checkProperties.push(propName); this.propertyOutputs.push(outputName); break; case '&': this.outputs.push(outputName); this.outputsRename.push(outputNameRename); this.propertyMap[outputName] = propName; break; default: let json = JSON.stringify(context); throw new Error( `Unexpected mapping '${bindingType}' in '${json}' in '${this.name}' directive.`, ); } }); } } /** * Upgrade ng1 components into Angular. */ static resolve( exportedComponents: {[name: string]: UpgradeNg1ComponentAdapterBuilder}, $injector: IInjectorService, ): Promise<string[]> { const promises = Object.entries(exportedComponents).map(([name, exportedComponent]) => { exportedComponent.directive = UpgradeHelper.getDirective($injector, name); exportedComponent.extractBindings(); return Promise.resolve( UpgradeHelper.getTemplate($injector, exportedComponent.directive, true), ).then((template) => (exportedComponent.template = template)); }); return Promise.all(promises); } }
{ "end_byte": 5272, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/src/upgrade_ng1_adapter.ts" }
angular/packages/upgrade/src/dynamic/src/upgrade_ng1_adapter.ts_5274_9856
@Directive() class UpgradeNg1ComponentAdapter implements OnInit, OnChanges, DoCheck { private controllerInstance: IControllerInstance | null = null; destinationObj: IBindingDestination | null = null; checkLastValues: any[] = []; directive: IDirective; element: Element; $element: any = null; componentScope: IScope; constructor( private helper: UpgradeHelper, scope: IScope, private template: string, private inputs: string[], private outputs: string[], private propOuts: string[], private checkProperties: string[], private propertyMap: {[key: string]: string}, ) { this.directive = helper.directive; this.element = helper.element; this.$element = helper.$element; this.componentScope = scope.$new(!!this.directive.scope); const controllerType = this.directive.controller; if (this.directive.bindToController && controllerType) { this.controllerInstance = this.helper.buildController(controllerType, this.componentScope); this.destinationObj = this.controllerInstance; } else { this.destinationObj = this.componentScope; } for (const input of this.inputs) { (this as any)[input] = null; } for (const output of this.outputs) { const emitter = ((this as any)[output] = new EventEmitter()); if (this.propOuts.indexOf(output) === -1) { this.setComponentProperty( output, ( (emitter) => (value: any) => emitter.emit(value) )(emitter), ); } } this.checkLastValues.push(...Array(propOuts.length).fill(INITIAL_VALUE)); } ngOnInit() { // Collect contents, insert and compile template const attachChildNodes: ILinkFn | undefined = this.helper.prepareTransclusion(); const linkFn = this.helper.compileTemplate(trustedHTMLFromLegacyTemplate(this.template)); // Instantiate controller (if not already done so) const controllerType = this.directive.controller; const bindToController = this.directive.bindToController; if (controllerType && !bindToController) { this.controllerInstance = this.helper.buildController(controllerType, this.componentScope); } // Require other controllers const requiredControllers = this.helper.resolveAndBindRequiredControllers( this.controllerInstance, ); // Hook: $onInit if (this.controllerInstance && isFunction(this.controllerInstance.$onInit)) { this.controllerInstance.$onInit(); } // Linking const link = this.directive.link; const preLink = typeof link == 'object' && link.pre; const postLink = typeof link == 'object' ? link.post : link; const attrs: IAttributes = NOT_SUPPORTED; const transcludeFn: ITranscludeFunction = NOT_SUPPORTED; if (preLink) { preLink(this.componentScope, this.$element, attrs, requiredControllers, transcludeFn); } linkFn(this.componentScope, null!, {parentBoundTranscludeFn: attachChildNodes}); if (postLink) { postLink(this.componentScope, this.$element, attrs, requiredControllers, transcludeFn); } // Hook: $postLink if (this.controllerInstance && isFunction(this.controllerInstance.$postLink)) { this.controllerInstance.$postLink(); } } ngOnChanges(changes: SimpleChanges) { const ng1Changes: any = {}; Object.keys(changes).forEach((propertyMapName) => { const change: SimpleChange = changes[propertyMapName]; this.setComponentProperty(propertyMapName, change.currentValue); ng1Changes[this.propertyMap[propertyMapName]] = change; }); if (isFunction(this.destinationObj!.$onChanges)) { this.destinationObj!.$onChanges!(ng1Changes); } } ngDoCheck() { const destinationObj = this.destinationObj; const lastValues = this.checkLastValues; const checkProperties = this.checkProperties; const propOuts = this.propOuts; checkProperties.forEach((propName, i) => { const value = destinationObj![propName]; const last = lastValues[i]; if (!strictEquals(last, value)) { const eventEmitter: EventEmitter<any> = (this as any)[propOuts[i]]; eventEmitter.emit((lastValues[i] = value)); } }); if (this.controllerInstance && isFunction(this.controllerInstance.$doCheck)) { this.controllerInstance.$doCheck(); } } ngOnDestroy() { this.helper.onDestroy(this.componentScope, this.controllerInstance); } setComponentProperty(name: string, value: any) { this.destinationObj![this.propertyMap[name]] = value; } }
{ "end_byte": 9856, "start_byte": 5274, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/dynamic/src/upgrade_ng1_adapter.ts" }
angular/packages/upgrade/src/common/BUILD.bazel_0_420
load("//tools:defaults.bzl", "ts_library") package(default_visibility = [ "//packages:__pkg__", "//packages/upgrade:__subpackages__", "//tools/public_api_guard:__subpackages__", ]) ts_library( name = "common", srcs = glob([ "src/**/*.ts", ]), deps = [ "//packages/core", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "src/**/*.ts", ]), )
{ "end_byte": 420, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/BUILD.bazel" }
angular/packages/upgrade/src/common/test/downgrade_injectable_spec.ts_0_2723
/** * @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 {Injector} from '@angular/core'; import * as angular from '../src/angular1'; import {$INJECTOR, INJECTOR_KEY, UPGRADE_APP_TYPE_KEY} from '../src/constants'; import {downgradeInjectable} from '../src/downgrade_injectable'; import {UpgradeAppType} from '../src/util'; describe('downgradeInjectable', () => { const setupMockInjectors = (downgradedModule = '') => { const mockNg1Injector = jasmine.createSpyObj<angular.IInjectorService>(['get', 'has']); mockNg1Injector.get.and.callFake((key: string) => mockDependencies[key]); mockNg1Injector.has.and.callFake((key: string) => mockDependencies.hasOwnProperty(key)); const mockNg2Injector = jasmine.createSpyObj<Injector>(['get']); mockNg2Injector.get.and.returnValue('service value'); const mockDependencies: {[key: string]: any} = { [UPGRADE_APP_TYPE_KEY]: downgradedModule ? UpgradeAppType.Lite : UpgradeAppType.Static, [`${INJECTOR_KEY}${downgradedModule}`]: mockNg2Injector, }; return {mockNg1Injector, mockNg2Injector}; }; it('should return an AngularJS annotated factory for the token', () => { const factory = downgradeInjectable('someToken'); expect(factory).toEqual(jasmine.any(Function)); expect((factory as any).$inject).toEqual([$INJECTOR]); const {mockNg1Injector, mockNg2Injector} = setupMockInjectors(); expect(factory(mockNg1Injector)).toEqual('service value'); expect(mockNg2Injector.get).toHaveBeenCalledWith('someToken'); }); it("should inject the specified module's injector when specifying a module name", () => { const factory = downgradeInjectable('someToken', 'someModule'); expect(factory).toEqual(jasmine.any(Function)); expect((factory as any).$inject).toEqual([$INJECTOR]); const {mockNg1Injector, mockNg2Injector} = setupMockInjectors('someModule'); expect(factory(mockNg1Injector)).toEqual('service value'); expect(mockNg2Injector.get).toHaveBeenCalledWith('someToken'); }); it("should mention the injectable's name in the error thrown when failing to retrieve injectable", () => { const factory = downgradeInjectable('someToken'); expect(factory).toEqual(jasmine.any(Function)); expect((factory as any).$inject).toEqual([$INJECTOR]); const {mockNg1Injector, mockNg2Injector} = setupMockInjectors(); mockNg2Injector.get.and.throwError('Mock failure'); expect(() => factory(mockNg1Injector)).toThrowError( /^Error while instantiating injectable 'someToken': Mock failure/, ); }); });
{ "end_byte": 2723, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/test/downgrade_injectable_spec.ts" }
angular/packages/upgrade/src/common/test/downgrade_component_adapter_spec.ts_0_7654
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Compiler, Component, ComponentFactory, Injector, NgModule, TestabilityRegistry, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import * as angular from '../src/angular1'; import {DowngradeComponentAdapter, groupNodesBySelector} from '../src/downgrade_component_adapter'; import {nodes, withEachNg1Version} from './helpers/common_test_helpers'; withEachNg1Version(() => { describe('DowngradeComponentAdapter', () => { describe('groupNodesBySelector', () => { it('should return an array of node collections for each selector', () => { const contentNodes = nodes( '<div class="x"><span>div-1 content</span></div>' + '<input type="number" name="myNum">' + '<input type="date" name="myDate">' + '<span>span content</span>' + '<div class="x"><span>div-2 content</span></div>', ); const selectors = ['input[type=date]', 'span', '.x']; const projectableNodes = groupNodesBySelector(selectors, contentNodes); expect(projectableNodes[0]).toEqual(nodes('<input type="date" name="myDate">')); expect(projectableNodes[1]).toEqual(nodes('<span>span content</span>')); expect(projectableNodes[2]).toEqual( nodes( '<div class="x"><span>div-1 content</span></div>' + '<div class="x"><span>div-2 content</span></div>', ), ); }); it('should collect up unmatched nodes for the wildcard selector', () => { const contentNodes = nodes( '<div class="x"><span>div-1 content</span></div>' + '<input type="number" name="myNum">' + '<input type="date" name="myDate">' + '<span>span content</span>' + '<div class="x"><span>div-2 content</span></div>', ); const selectors = ['.x', '*', 'input[type=date]']; const projectableNodes = groupNodesBySelector(selectors, contentNodes); expect(projectableNodes[0]).toEqual( nodes( '<div class="x"><span>div-1 content</span></div>' + '<div class="x"><span>div-2 content</span></div>', ), ); expect(projectableNodes[1]).toEqual( nodes('<input type="number" name="myNum">' + '<span>span content</span>'), ); expect(projectableNodes[2]).toEqual(nodes('<input type="date" name="myDate">')); }); it('should return an array of empty arrays if there are no nodes passed in', () => { const selectors = ['.x', '*', 'input[type=date]']; const projectableNodes = groupNodesBySelector(selectors, []); expect(projectableNodes).toEqual([[], [], []]); }); it('should return an empty array for each selector that does not match', () => { const contentNodes = nodes( '<div class="x"><span>div-1 content</span></div>' + '<input type="number" name="myNum">' + '<input type="date" name="myDate">' + '<span>span content</span>' + '<div class="x"><span>div-2 content</span></div>', ); const projectableNodes = groupNodesBySelector([], contentNodes); expect(projectableNodes).toEqual([]); const noMatchSelectorNodes = groupNodesBySelector(['.not-there'], contentNodes); expect(noMatchSelectorNodes).toEqual([[]]); }); }); describe('testability', () => { let adapter: DowngradeComponentAdapter; let content: string; let compiler: Compiler; let registry: TestabilityRegistry; let element: angular.IAugmentedJQuery; class mockScope implements angular.IScope { private destroyListeners: (() => void)[] = []; $new() { return this; } $watch(exp: angular.Ng1Expression, fn?: (a1?: any, a2?: any) => void) { return () => {}; } $on(event: string, fn?: (event?: any, ...args: any[]) => void) { if (event === '$destroy' && fn) { this.destroyListeners.push(fn); } return () => {}; } $destroy() { let listener: (() => void) | undefined; while ((listener = this.destroyListeners.shift())) listener(); } $apply(exp?: angular.Ng1Expression) { return () => {}; } $digest() { return () => {}; } $evalAsync(exp: angular.Ng1Expression, locals?: any) { return () => {}; } $$childTail!: angular.IScope; $$childHead!: angular.IScope; $$nextSibling!: angular.IScope; [key: string]: any; $id = 'mockScope'; $parent!: angular.IScope; $root!: angular.IScope; $$phase: any; } function getAdaptor(): DowngradeComponentAdapter { let attrs = undefined as any; let scope: angular.IScope; // mock let ngModel = undefined as any; let parentInjector: Injector; // testbed let $compile = undefined as any; let $parse = undefined as any; let componentFactory: ComponentFactory<any>; // testbed let wrapCallback = (cb: any) => cb; content = ` <h1> new component </h1> <div> a great component </div> <comp></comp> `; element = angular.element(content); scope = new mockScope(); @Component({ selector: 'comp', template: '', standalone: false, }) class NewComponent {} @NgModule({ providers: [{provide: 'hello', useValue: 'component'}], declarations: [NewComponent], }) class NewModule {} const modFactory = compiler.compileModuleSync(NewModule); const module = modFactory.create(TestBed); componentFactory = module.componentFactoryResolver.resolveComponentFactory(NewComponent)!; parentInjector = TestBed; return new DowngradeComponentAdapter( element, attrs, scope, ngModel, parentInjector, $compile, $parse, componentFactory, wrapCallback, /* unsafelyOverwriteSignalInputs */ false, ); } beforeEach(() => { compiler = TestBed.inject(Compiler); registry = TestBed.inject(TestabilityRegistry); adapter = getAdaptor(); }); beforeEach(() => registry.unregisterAllApplications()); afterEach(() => registry.unregisterAllApplications()); it('should add testabilities hook when creating components', () => { let registry = TestBed.inject(TestabilityRegistry); adapter.createComponentAndSetup([]); expect(registry.getAllTestabilities().length).toEqual(1); adapter = getAdaptor(); // get a new adaptor to creat a new component adapter.createComponentAndSetup([]); expect(registry.getAllTestabilities().length).toEqual(2); }); it('should remove the testability hook when destroy a component', () => { const registry = TestBed.inject(TestabilityRegistry); expect(registry.getAllTestabilities().length).toEqual(0); adapter.createComponentAndSetup([]); expect(registry.getAllTestabilities().length).toEqual(1); element.remove!(); expect(registry.getAllTestabilities().length).toEqual(0); }); }); }); });
{ "end_byte": 7654, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/test/downgrade_component_adapter_spec.ts" }
angular/packages/upgrade/src/common/test/promise_util_spec.ts_0_3536
/** * @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 {isThenable, SyncPromise} from '../src/promise_util'; describe('isThenable()', () => { it('should return false for primitive values', () => { expect(isThenable(undefined)).toBe(false); expect(isThenable(null)).toBe(false); expect(isThenable(false)).toBe(false); expect(isThenable(true)).toBe(false); expect(isThenable(0)).toBe(false); expect(isThenable(1)).toBe(false); expect(isThenable('')).toBe(false); expect(isThenable('foo')).toBe(false); }); it('should return false if `.then` is not a function', () => { expect(isThenable([])).toBe(false); expect(isThenable(['then'])).toBe(false); expect(isThenable(function () {})).toBe(false); expect(isThenable({})).toBe(false); expect(isThenable({then: true})).toBe(false); expect(isThenable({then: 'not a function'})).toBe(false); }); it('should return true if `.then` is a function', () => { expect(isThenable({then: function () {}})).toBe(true); expect(isThenable({then: () => {}})).toBe(true); expect(isThenable(Object.assign('thenable', {then: () => {}}))).toBe(true); }); }); describe('SyncPromise', () => { it('should call all callbacks once resolved', () => { const spy1 = jasmine.createSpy('spy1'); const spy2 = jasmine.createSpy('spy2'); const promise = new SyncPromise<string>(); promise.then(spy1); promise.then(spy2); expect(spy1).not.toHaveBeenCalled(); expect(spy2).not.toHaveBeenCalled(); promise.resolve('foo'); expect(spy1).toHaveBeenCalledWith('foo'); expect(spy2).toHaveBeenCalledWith('foo'); }); it('should call callbacks immediately if already resolved', () => { const spy = jasmine.createSpy('spy'); const promise = new SyncPromise<string>(); promise.resolve('foo'); promise.then(spy); expect(spy).toHaveBeenCalledWith('foo'); }); it('should ignore subsequent calls to `resolve()`', () => { const spy = jasmine.createSpy('spy'); const promise = new SyncPromise<string>(); promise.then(spy); promise.resolve('foo'); expect(spy).toHaveBeenCalledWith('foo'); spy.calls.reset(); promise.resolve('bar'); expect(spy).not.toHaveBeenCalled(); promise.then(spy); promise.resolve('baz'); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenCalledWith('foo'); }); describe('.all()', () => { it('should return a `SyncPromise` instance', () => { expect(SyncPromise.all([])).toEqual(jasmine.any(SyncPromise)); }); it('should resolve immediately if the provided values are not thenable', () => { const spy = jasmine.createSpy('spy'); const promise = SyncPromise.all(['foo', 1, {then: false}, []]); promise.then(spy); expect(spy).toHaveBeenCalledWith(['foo', 1, {then: false}, []]); }); it('should wait for any thenables to resolve', async () => { const spy = jasmine.createSpy('spy'); const v1 = 'foo'; const v2 = new SyncPromise<string>(); const v3 = Promise.resolve('baz'); const promise = SyncPromise.all([v1, v2, v3]); promise.then(spy); expect(spy).not.toHaveBeenCalled(); v2.resolve('bar'); expect(spy).not.toHaveBeenCalled(); await v3; expect(spy).toHaveBeenCalledWith(['foo', 'bar', 'baz']); }); }); });
{ "end_byte": 3536, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/test/promise_util_spec.ts" }
angular/packages/upgrade/src/common/test/BUILD.bazel_0_710
load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/upgrade/index.mjs", deps = ["//packages/upgrade"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages/core", "//packages/core/testing", "//packages/upgrade/src/common", "//packages/upgrade/src/common/test/helpers", ], ) karma_web_test_suite( name = "test", static_files = [ "//:angularjs_scripts", ], deps = [ ":test_lib", ], )
{ "end_byte": 710, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/test/BUILD.bazel" }
angular/packages/upgrade/src/common/test/component_info_spec.ts_0_1419
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {PropertyBinding} from '../src/component_info'; describe('PropertyBinding', () => { it('should process a simple binding', () => { const binding = new PropertyBinding('someBinding', 'someBinding'); expect(binding.prop).toEqual('someBinding'); expect(binding.attr).toEqual('someBinding'); expect(binding.bracketAttr).toEqual('[someBinding]'); expect(binding.bracketParenAttr).toEqual('[(someBinding)]'); expect(binding.parenAttr).toEqual('(someBinding)'); expect(binding.onAttr).toEqual('onSomeBinding'); expect(binding.bindAttr).toEqual('bindSomeBinding'); expect(binding.bindonAttr).toEqual('bindonSomeBinding'); }); it('should process a two-part binding', () => { const binding = new PropertyBinding('someProp', 'someAttr'); expect(binding.prop).toEqual('someProp'); expect(binding.attr).toEqual('someAttr'); expect(binding.bracketAttr).toEqual('[someAttr]'); expect(binding.bracketParenAttr).toEqual('[(someAttr)]'); expect(binding.parenAttr).toEqual('(someAttr)'); expect(binding.onAttr).toEqual('onSomeAttr'); expect(binding.bindAttr).toEqual('bindSomeAttr'); expect(binding.bindonAttr).toEqual('bindonSomeAttr'); }); });
{ "end_byte": 1419, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/test/component_info_spec.ts" }
angular/packages/upgrade/src/common/test/helpers/BUILD.bazel_0_288
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//packages/upgrade:__subpackages__"]) ts_library( name = "helpers", srcs = glob([ "*.ts", ]), deps = [ "//packages/core/testing", "//packages/upgrade/src/common", ], )
{ "end_byte": 288, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/test/helpers/BUILD.bazel" }
angular/packages/upgrade/src/common/test/helpers/common_test_helpers.ts_0_7492
/** * @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 {setAngularJSGlobal} from '../../src/angular1'; // Whether the upgrade tests should run against AngularJS minified or not. This can be // temporarily switched to "false" in order to make it easy to debug AngularJS locally. const TEST_MINIFIED = true; const ANGULARJS_FILENAME = TEST_MINIFIED ? 'angular.min.js' : 'angular.js'; const ng1Versions = [ { label: '1.5', files: [`angular-1.5/${ANGULARJS_FILENAME}`, 'angular-mocks-1.5/angular-mocks.js'], }, { label: '1.6', files: [`angular-1.6/${ANGULARJS_FILENAME}`, 'angular-mocks-1.6/angular-mocks.js'], }, { label: '1.7', files: [`angular-1.7/${ANGULARJS_FILENAME}`, 'angular-mocks-1.7/angular-mocks.js'], }, { label: '1.8', files: [`angular-1.8/${ANGULARJS_FILENAME}`, 'angular-mocks-1.8/angular-mocks.js'], }, ]; export function createWithEachNg1VersionFn(setNg1: typeof setAngularJSGlobal) { return (specSuite: () => void) => ng1Versions.forEach(({label, files}) => { describe(`[AngularJS v${label}]`, () => { // Problem: // As soon as `angular-mocks.js` is loaded, it runs `beforeEach` and `afterEach` to register // setup/tear down callbacks. Jasmine 2.9+ does not allow `beforeEach`/`afterEach` to be // nested inside a `beforeAll` call (only inside `describe`). // Hacky work-around: // Patch the affected jasmine methods while loading `angular-mocks.js` (inside `beforeAll`) to // capture the registered callbacks. Also, inside the `describe` call register a callback with // each affected method that runs all captured callbacks. // (Note: Currently, async callbacks are not supported, but that should be OK, since // `angular-mocks.js` does not use them.) const methodsToPatch = ['beforeAll', 'beforeEach', 'afterEach', 'afterAll']; const methodCallbacks = methodsToPatch.reduce<{[name: string]: any[]}>( (aggr, method) => ({...aggr, [method]: []}), {}, ); const win = window as any; function patchJasmineMethods(): () => void { const originalMethods: {[name: string]: any} = {}; methodsToPatch.forEach((method) => { originalMethods[method] = win[method]; win[method] = (cb: any) => methodCallbacks[method].push(cb); }); return () => methodsToPatch.forEach((method) => (win[method] = originalMethods[method])); } function loadScript(scriptUrl: string, retry = 0): Promise<void> { return new Promise<void>((resolve, reject) => { const script = document.createElement('script'); script.async = true; script.onerror = retry > 0 ? () => { // Sometimes (especially on mobile browsers on SauceLabs) the script may fail to load // due to a temporary issue with the internet connection. To avoid flakes on CI when // this happens, we retry the download after some delay. const delay = 5000; win.console.warn( `\n[${new Date().toISOString()}] Retrying to load "${scriptUrl}" in ${delay}ms...`, ); script.remove(); setTimeout(() => loadScript(scriptUrl, --retry).then(resolve, reject), delay); } : () => { // Whenever the script failed loading, browsers will just pass an "ErrorEvent" which // does not contain useful information on most browsers we run tests against. In order // to avoid writing logic to convert the event into a readable error and since just // passing the event might cause people to spend unnecessary time debugging the // "ErrorEvent", we create a simple error that doesn't imply that there is a lot of // information within the "ErrorEvent". reject(`An error occurred while loading "${scriptUrl}".`); }; script.onload = () => { script.remove(); resolve(); }; script.src = `base/npm/node_modules/${scriptUrl}`; document.body.appendChild(script); }); } beforeAll((done) => { const restoreJasmineMethods = patchJasmineMethods(); const onSuccess = () => { restoreJasmineMethods(); done(); }; const onError = (err: any) => { restoreJasmineMethods(); done.fail(err); }; // Load AngularJS before running tests. files .reduce((prev, file) => prev.then(() => loadScript(file, 1)), Promise.resolve()) .then(() => setNg1(win.angular)) .then(onSuccess, onError); // When Saucelabs is flaky, some browsers (esp. mobile) take some time to load and execute // the AngularJS scripts. Specifying a higher timeout here, reduces flaky-ness. }, 60000); afterAll(() => { // `win.angular` will not be defined if loading the script in `berofeAll()` failed. In that // case, avoid causing another error in `afterAll()`, because the reporter only shows the // most recent error (thus hiding the original, possibly more informative, error message). if (win.angular) { // In these tests we are loading different versions of AngularJS on the same window. // AngularJS leaves an "expandoId" property on `document`, which can trick subsequent // `window.angular` instances into believing an app is already bootstrapped. win.angular.element.cleanData([document]); } // Remove AngularJS to leave a clean state for subsequent tests. setNg1(undefined); delete win.angular; }); methodsToPatch.forEach((method) => win[method](function (this: unknown) { // Run the captured callbacks. (Async callbacks not supported.) methodCallbacks[method].forEach((cb) => cb.call(this)); }), ); specSuite(); }); }); } export function html(html: string): Element { // Don't return `body` itself, because using it as a `$rootElement` for ng1 // will attach `$injector` to it and that will affect subsequent tests. const body = document.body; body.innerHTML = `<div>${html.trim()}</div>`; const div = document.body.firstChild as Element; if (div.childNodes.length === 1 && div.firstChild instanceof HTMLElement) { return div.firstChild; } return div; } export function multiTrim(text: string | null | undefined, allSpace = false): string { if (typeof text == 'string') { const repl = allSpace ? '' : ' '; return text.replace(/\n/g, '').replace(/\s+/g, repl).trim(); } throw new Error('Argument can not be undefined.'); } export function nodes(html: string) { const div = document.createElement('div'); div.innerHTML = html.trim(); return Array.prototype.slice.call(div.childNodes); } export const withEachNg1Version = createWithEachNg1VersionFn(setAngularJSGlobal);
{ "end_byte": 7492, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/test/helpers/common_test_helpers.ts" }
angular/packages/upgrade/src/common/src/promise_util.ts_0_1614
/** * @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 {isFunction} from './util'; export interface Thenable<T> { then(callback: (value: T) => any): any; } export function isThenable<T>(obj: unknown): obj is Thenable<T> { return !!obj && isFunction((obj as any).then); } /** * Synchronous, promise-like object. */ export class SyncPromise<T> { protected value: T | undefined; private resolved = false; private callbacks: ((value: T) => unknown)[] = []; static all<T>(valuesOrPromises: (T | Thenable<T>)[]): SyncPromise<T[]> { const aggrPromise = new SyncPromise<T[]>(); let resolvedCount = 0; const results: T[] = []; const resolve = (idx: number, value: T) => { results[idx] = value; if (++resolvedCount === valuesOrPromises.length) aggrPromise.resolve(results); }; valuesOrPromises.forEach((p, idx) => { if (isThenable(p)) { p.then((v) => resolve(idx, v)); } else { resolve(idx, p); } }); return aggrPromise; } resolve(value: T): void { // Do nothing, if already resolved. if (this.resolved) return; this.value = value; this.resolved = true; // Run the queued callbacks. this.callbacks.forEach((callback) => callback(value)); this.callbacks.length = 0; } then(callback: (value: T) => unknown): void { if (this.resolved) { callback(this.value!); } else { this.callbacks.push(callback); } } }
{ "end_byte": 1614, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/promise_util.ts" }
angular/packages/upgrade/src/common/src/downgrade_injectable.ts_0_3762
/** * @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 {Injector} from '@angular/core'; import {IInjectorService} from './angular1'; import {$INJECTOR, INJECTOR_KEY} from './constants'; import {getTypeName, isFunction, validateInjectionKey} from './util'; /** * @description * * A helper function to allow an Angular service to be accessible from AngularJS. * * *Part of the [upgrade/static](api?query=upgrade%2Fstatic) * library for hybrid upgrade apps that support AOT compilation* * * This helper function returns a factory function that provides access to the Angular * service identified by the `token` parameter. * * @usageNotes * ### Examples * * First ensure that the service to be downgraded is provided in an `NgModule` * that will be part of the upgrade application. For example, let's assume we have * defined `HeroesService` * * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-service"} * * and that we have included this in our upgrade app `NgModule` * * {@example upgrade/static/ts/full/module.ts region="ng2-module"} * * Now we can register the `downgradeInjectable` factory function for the service * on an AngularJS module. * * {@example upgrade/static/ts/full/module.ts region="downgrade-ng2-heroes-service"} * * Inside an AngularJS component's controller we can get hold of the * downgraded service via the name we gave when downgrading. * * {@example upgrade/static/ts/full/module.ts region="example-app"} * * <div class="alert is-important"> * * When using `downgradeModule()`, downgraded injectables will not be available until the Angular * module that provides them is instantiated. In order to be safe, you need to ensure that the * downgraded injectables are not used anywhere _outside_ the part of the app where it is * guaranteed that their module has been instantiated. * * For example, it is _OK_ to use a downgraded service in an upgraded component that is only used * from a downgraded Angular component provided by the same Angular module as the injectable, but * it is _not OK_ to use it in an AngularJS component that may be used independently of Angular or * use it in a downgraded Angular component from a different module. * * </div> * * @param token an `InjectionToken` that identifies a service provided from Angular. * @param downgradedModule the name of the downgraded module (if any) that the injectable * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose injector will * be used for instantiating the injectable.<br /> * (This option is only necessary when using `downgradeModule()` to downgrade more than one Angular * module.) * * @returns a [factory function](https://docs.angularjs.org/guide/di) that can be * used to register the service on an AngularJS module. * * @publicApi */ export function downgradeInjectable(token: any, downgradedModule: string = ''): Function { const factory = function ($injector: IInjectorService) { const injectorKey = `${INJECTOR_KEY}${downgradedModule}`; const injectableName = isFunction(token) ? getTypeName(token) : String(token); const attemptedAction = `instantiating injectable '${injectableName}'`; validateInjectionKey($injector, downgradedModule, injectorKey, attemptedAction); try { const injector: Injector = $injector.get(injectorKey); return injector.get(token); } catch (err) { throw new Error(`Error while ${attemptedAction}: ${(err as Error).message || err}`); } }; (factory as any)['$inject'] = [$INJECTOR]; return factory; }
{ "end_byte": 3762, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/downgrade_injectable.ts" }
angular/packages/upgrade/src/common/src/angular1.ts_0_6926
/** * @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 type Ng1Token = string; export type Ng1Expression = string | Function; export interface IAnnotatedFunction extends Function { // Older versions of `@types/angular` typings extend the global `Function` interface with // `$inject?: string[]`, which is not compatible with `$inject?: ReadonlyArray<string>` (used in // latest versions). $inject?: Function extends {$inject?: string[]} ? Ng1Token[] : ReadonlyArray<Ng1Token>; } export type IInjectable = (Ng1Token | Function)[] | IAnnotatedFunction; export type SingleOrListOrMap<T> = T | T[] | {[key: string]: T}; export interface IModule { name: string; requires: (string | IInjectable)[]; config(fn: IInjectable): IModule; directive(selector: string, factory: IInjectable): IModule; component(selector: string, component: IComponent): IModule; controller(name: string, type: IInjectable): IModule; factory(key: Ng1Token, factoryFn: IInjectable): IModule; value(key: Ng1Token, value: any): IModule; constant(token: Ng1Token, value: any): IModule; run(a: IInjectable): IModule; } export interface ICompileService { (element: Element | NodeList | Node[] | string, transclude?: Function): ILinkFn; } export interface ILinkFn { (scope: IScope, cloneAttachFn?: ICloneAttachFunction, options?: ILinkFnOptions): IAugmentedJQuery; $$slots?: {[slotName: string]: ILinkFn}; } export interface ILinkFnOptions { parentBoundTranscludeFn?: Function; transcludeControllers?: {[key: string]: any}; futureParentElement?: Node; } export interface IRootScopeService { $new(isolate?: boolean): IScope; $id: string; $parent: IScope; $root: IScope; $watch(exp: Ng1Expression, fn?: (a1?: any, a2?: any) => void): Function; $on(event: string, fn?: (event?: any, ...args: any[]) => void): Function; $destroy(): any; $apply(exp?: Ng1Expression): any; $digest(): any; $evalAsync(exp: Ng1Expression, locals?: any): void; $on(event: string, fn?: (event?: any, ...args: any[]) => void): Function; $$childTail: IScope; $$childHead: IScope; $$nextSibling: IScope; $$phase: any; [key: string]: any; } export interface IScope extends IRootScopeService {} export interface IAngularBootstrapConfig { strictDi?: boolean; } export interface IDirective { compile?: IDirectiveCompileFn; controller?: IController; controllerAs?: string; bindToController?: boolean | {[key: string]: string}; link?: IDirectiveLinkFn | IDirectivePrePost; name?: string; priority?: number; replace?: boolean; require?: DirectiveRequireProperty; restrict?: string; scope?: boolean | {[key: string]: string}; template?: string | Function; templateUrl?: string | Function; templateNamespace?: string; terminal?: boolean; transclude?: DirectiveTranscludeProperty; } export type DirectiveRequireProperty = SingleOrListOrMap<string>; export type DirectiveTranscludeProperty = boolean | 'element' | {[key: string]: string}; export interface IDirectiveCompileFn { ( templateElement: IAugmentedJQuery, templateAttributes: IAttributes, transclude: ITranscludeFunction, ): IDirectivePrePost; } export interface IDirectivePrePost { pre?: IDirectiveLinkFn; post?: IDirectiveLinkFn; } export interface IDirectiveLinkFn { ( scope: IScope, instanceElement: IAugmentedJQuery, instanceAttributes: IAttributes, controller: any, transclude: ITranscludeFunction, ): void; } export interface IComponent { bindings?: {[key: string]: string}; controller?: string | IInjectable; controllerAs?: string; require?: DirectiveRequireProperty; template?: string | Function; templateUrl?: string | Function; transclude?: DirectiveTranscludeProperty; } export interface IAttributes { $observe(attr: string, fn: (v: string) => void): void; [key: string]: any; } export interface ITranscludeFunction { // If the scope is provided, then the cloneAttachFn must be as well. (scope: IScope, cloneAttachFn: ICloneAttachFunction): IAugmentedJQuery; // If one argument is provided, then it's assumed to be the cloneAttachFn. (cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; } export interface ICloneAttachFunction { (clonedElement: IAugmentedJQuery, scope: IScope): any; } export type IAugmentedJQuery = Node[] & { on?: (name: string, fn: () => void) => void; data?: (name: string, value?: any) => any; text?: () => string; inheritedData?: (name: string, value?: any) => any; children?: () => IAugmentedJQuery; contents?: () => IAugmentedJQuery; parent?: () => IAugmentedJQuery; empty?: () => void; append?: (content: IAugmentedJQuery | string) => IAugmentedJQuery; controller?: (name: string) => any; isolateScope?: () => IScope; injector?: () => IInjectorService; triggerHandler?: (eventTypeOrObject: string | Event, extraParameters?: any[]) => IAugmentedJQuery; remove?: () => void; removeData?: () => void; }; export interface IProvider { $get: IInjectable; } export interface IProvideService { provider(token: Ng1Token, provider: IProvider): IProvider; factory(token: Ng1Token, factory: IInjectable): IProvider; service(token: Ng1Token, type: IInjectable): IProvider; value(token: Ng1Token, value: any): IProvider; constant(token: Ng1Token, value: any): void; decorator(token: Ng1Token, factory: IInjectable): void; } export interface IParseService { (expression: string): ICompiledExpression; } export interface ICompiledExpression { (context: any, locals: any): any; assign?: (context: any, value: any) => any; } export interface IHttpBackendService { ( method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean, ): void; } export interface ICacheObject { put<T>(key: string, value?: T): T; get(key: string): any; } export interface ITemplateCacheService extends ICacheObject {} export type IController = string | IInjectable; export interface IControllerService { (controllerConstructor: IController, locals?: any, later?: any, ident?: any): any; (controllerName: string, locals?: any): any; } export interface IInjectorService { get(key: string): any; has(key: string): boolean; } export interface IIntervalService { ( func: Function, delay: number, count?: number, invokeApply?: boolean, ...args: any[] ): Promise<any>; cancel(promise: Promise<any>): boolean; } export interface ITestabilityService { findBindings(element: Element, expression: string, opt_exactMatch?: boolean): Element[]; findModels(element: Element, expression: string, opt_exactMatch?: boolean): Element[]; getLocation(): string; setLocation(url: string): void; whenStable(callback: Function): void; }
{ "end_byte": 6926, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/angular1.ts" }
angular/packages/upgrade/src/common/src/angular1.ts_6928_10230
export interface INgModelController { $render(): void; $isEmpty(value: any): boolean; $setValidity(validationErrorKey: string, isValid: boolean): void; $setPristine(): void; $setDirty(): void; $setUntouched(): void; $setTouched(): void; $rollbackViewValue(): void; $validate(): void; $commitViewValue(): void; $setViewValue(value: any, trigger: string): void; $viewValue: any; $modelValue: any; $parsers: Function[]; $formatters: Function[]; $validators: {[key: string]: Function}; $asyncValidators: {[key: string]: Function}; $viewChangeListeners: Function[]; $error: Object; $pending: Object; $untouched: boolean; $touched: boolean; $pristine: boolean; $dirty: boolean; $valid: boolean; $invalid: boolean; $name: string; } function noNg(): never { throw new Error('AngularJS v1.x is not loaded!'); } const noNgElement: typeof angular.element = (() => noNg()) as any; noNgElement.cleanData = noNg; let angular: { bootstrap: ( e: Element, modules: (string | IInjectable)[], config?: IAngularBootstrapConfig, ) => IInjectorService; module: (prefix: string, dependencies?: string[]) => IModule; element: { (e: string | Element | Document | IAugmentedJQuery): IAugmentedJQuery; cleanData: (nodes: Node[] | NodeList) => void; }; injector: (modules: Array<string | IInjectable>, strictDi?: boolean) => IInjectorService; version: {major: number}; resumeBootstrap: () => void; getTestability: (e: Element) => ITestabilityService; } = { bootstrap: noNg, module: noNg, element: noNgElement, injector: noNg, version: undefined as any, resumeBootstrap: noNg, getTestability: noNg, }; try { if (window.hasOwnProperty('angular')) { angular = (<any>window).angular; } } catch { // ignore in CJS mode. } /** * @deprecated Use `setAngularJSGlobal` instead. * * @publicApi */ export function setAngularLib(ng: any): void { setAngularJSGlobal(ng); } /** * @deprecated Use `getAngularJSGlobal` instead. * * @publicApi */ export function getAngularLib(): any { return getAngularJSGlobal(); } /** * Resets the AngularJS global. * * Used when AngularJS is loaded lazily, and not available on `window`. * * @publicApi */ export function setAngularJSGlobal(ng: any): void { angular = ng; } /** * Returns the current AngularJS global. * * @publicApi */ export function getAngularJSGlobal(): any { return angular; } export const bootstrap: typeof angular.bootstrap = (e, modules, config?) => angular.bootstrap(e, modules, config); // Do not declare as `module` to avoid webpack bug // (see https://github.com/angular/angular/issues/30050). export const module_: typeof angular.module = (prefix, dependencies?) => angular.module(prefix, dependencies); export const element: typeof angular.element = ((e) => angular.element(e)) as typeof angular.element; element.cleanData = (nodes) => angular.element.cleanData(nodes); export const injector: typeof angular.injector = ( modules: Array<string | IInjectable>, strictDi?: boolean, ) => angular.injector(modules, strictDi); export const resumeBootstrap: typeof angular.resumeBootstrap = () => angular.resumeBootstrap(); export const getTestability: typeof angular.getTestability = (e) => angular.getTestability(e);
{ "end_byte": 10230, "start_byte": 6928, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/angular1.ts" }
angular/packages/upgrade/src/common/src/upgrade_helper.ts_0_1265
/** * @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 {ElementRef, Injector, SimpleChanges} from '@angular/core'; import { DirectiveRequireProperty, element as angularElement, IAugmentedJQuery, ICloneAttachFunction, ICompileService, IController, IControllerService, IDirective, IHttpBackendService, IInjectorService, ILinkFn, IScope, ITemplateCacheService, SingleOrListOrMap, } from './angular1'; import {$COMPILE, $CONTROLLER, $HTTP_BACKEND, $INJECTOR, $TEMPLATE_CACHE} from './constants'; import {cleanData, controllerKey, directiveNormalize, isFunction} from './util'; import {TrustedHTML} from './security/trusted_types_defs'; import {trustedHTMLFromLegacyTemplate} from './security/trusted_types'; // Constants const REQUIRE_PREFIX_RE = /^(\^\^?)?(\?)?(\^\^?)?/; // Interfaces export interface IBindingDestination { [key: string]: any; $onChanges?: (changes: SimpleChanges) => void; } export interface IControllerInstance extends IBindingDestination { $doCheck?: () => void; $onDestroy?: () => void; $onInit?: () => void; $postLink?: () => void; } // Classes
{ "end_byte": 1265, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/upgrade_helper.ts" }
angular/packages/upgrade/src/common/src/upgrade_helper.ts_1266_10226
export class UpgradeHelper { public readonly $injector: IInjectorService; public readonly element: Element; public readonly $element: IAugmentedJQuery; public readonly directive: IDirective; private readonly $compile: ICompileService; private readonly $controller: IControllerService; constructor( injector: Injector, private name: string, elementRef: ElementRef, directive?: IDirective, ) { this.$injector = injector.get($INJECTOR); this.$compile = this.$injector.get($COMPILE); this.$controller = this.$injector.get($CONTROLLER); this.element = elementRef.nativeElement; this.$element = angularElement(this.element); this.directive = directive ?? UpgradeHelper.getDirective(this.$injector, name); } static getDirective($injector: IInjectorService, name: string): IDirective { const directives: IDirective[] = $injector.get(name + 'Directive'); if (directives.length > 1) { throw new Error(`Only support single directive definition for: ${name}`); } const directive = directives[0]; // AngularJS will transform `link: xyz` to `compile: () => xyz`. So we can only tell there was a // user-defined `compile` if there is no `link`. In other cases, we will just ignore `compile`. if (directive.compile && !directive.link) notSupported(name, 'compile'); if (directive.replace) notSupported(name, 'replace'); if (directive.terminal) notSupported(name, 'terminal'); return directive; } static getTemplate( $injector: IInjectorService, directive: IDirective, fetchRemoteTemplate = false, $element?: IAugmentedJQuery, ): string | TrustedHTML | Promise<string | TrustedHTML> { if (directive.template !== undefined) { return trustedHTMLFromLegacyTemplate(getOrCall<string>(directive.template, $element)); } else if (directive.templateUrl) { const $templateCache = $injector.get($TEMPLATE_CACHE) as ITemplateCacheService; const url = getOrCall<string>(directive.templateUrl, $element); const template = $templateCache.get(url); if (template !== undefined) { return trustedHTMLFromLegacyTemplate(template); } else if (!fetchRemoteTemplate) { throw new Error('loading directive templates asynchronously is not supported'); } return new Promise((resolve, reject) => { const $httpBackend = $injector.get($HTTP_BACKEND) as IHttpBackendService; $httpBackend('GET', url, null, (status: number, response: string) => { if (status === 200) { resolve(trustedHTMLFromLegacyTemplate($templateCache.put(url, response))); } else { reject(`GET component template from '${url}' returned '${status}: ${response}'`); } }); }); } else { throw new Error(`Directive '${directive.name}' is not a component, it is missing template.`); } } buildController(controllerType: IController, $scope: IScope) { // TODO: Document that we do not pre-assign bindings on the controller instance. // Quoted properties below so that this code can be optimized with Closure Compiler. const locals = {'$scope': $scope, '$element': this.$element}; const controller = this.$controller(controllerType, locals, null, this.directive.controllerAs); this.$element.data?.(controllerKey(this.directive.name!), controller); return controller; } compileTemplate(template?: string | TrustedHTML): ILinkFn { if (template === undefined) { template = UpgradeHelper.getTemplate(this.$injector, this.directive, false, this.$element) as | string | TrustedHTML; } return this.compileHtml(template); } onDestroy($scope: IScope, controllerInstance?: any) { if (controllerInstance && isFunction(controllerInstance.$onDestroy)) { controllerInstance.$onDestroy(); } $scope.$destroy(); cleanData(this.element); } prepareTransclusion(): ILinkFn | undefined { const transclude = this.directive.transclude; const contentChildNodes = this.extractChildNodes(); const attachChildrenFn: ILinkFn = (scope, cloneAttachFn) => { // Since AngularJS v1.5.8, `cloneAttachFn` will try to destroy the transclusion scope if // `$template` is empty. Since the transcluded content comes from Angular, not AngularJS, // there will be no transclusion scope here. // Provide a dummy `scope.$destroy()` method to prevent `cloneAttachFn` from throwing. scope = scope || {$destroy: () => undefined}; return cloneAttachFn!($template, scope); }; let $template = contentChildNodes; if (transclude) { const slots = Object.create(null); if (typeof transclude === 'object') { $template = []; const slotMap = Object.create(null); const filledSlots = Object.create(null); // Parse the element selectors. Object.keys(transclude).forEach((slotName) => { let selector = transclude[slotName]; const optional = selector.charAt(0) === '?'; selector = optional ? selector.substring(1) : selector; slotMap[selector] = slotName; slots[slotName] = null; // `null`: Defined but not yet filled. filledSlots[slotName] = optional; // Consider optional slots as filled. }); // Add the matching elements into their slot. contentChildNodes.forEach((node) => { const slotName = slotMap[directiveNormalize(node.nodeName.toLowerCase())]; if (slotName) { filledSlots[slotName] = true; slots[slotName] = slots[slotName] || []; slots[slotName].push(node); } else { $template.push(node); } }); // Check for required slots that were not filled. Object.keys(filledSlots).forEach((slotName) => { if (!filledSlots[slotName]) { throw new Error(`Required transclusion slot '${slotName}' on directive: ${this.name}`); } }); Object.keys(slots) .filter((slotName) => slots[slotName]) .forEach((slotName) => { const nodes = slots[slotName]; slots[slotName] = (scope: IScope, cloneAttach: ICloneAttachFunction) => { return cloneAttach!(nodes, scope); }; }); } // Attach `$$slots` to default slot transclude fn. attachChildrenFn.$$slots = slots; // AngularJS v1.6+ ignores empty or whitespace-only transcluded text nodes. But Angular // removes all text content after the first interpolation and updates it later, after // evaluating the expressions. This would result in AngularJS failing to recognize text // nodes that start with an interpolation as transcluded content and use the fallback // content instead. // To avoid this issue, we add a // [zero-width non-joiner character](https://en.wikipedia.org/wiki/Zero-width_non-joiner) // to empty text nodes (which can only be a result of Angular removing their initial content). // NOTE: Transcluded text content that starts with whitespace followed by an interpolation // will still fail to be detected by AngularJS v1.6+ $template.forEach((node) => { if (node.nodeType === Node.TEXT_NODE && !node.nodeValue) { node.nodeValue = '\u200C'; } }); } return attachChildrenFn; } resolveAndBindRequiredControllers(controllerInstance: IControllerInstance | null) { const directiveRequire = this.getDirectiveRequire(); const requiredControllers = this.resolveRequire(directiveRequire); if (controllerInstance && this.directive.bindToController && isMap(directiveRequire)) { const requiredControllersMap = requiredControllers as {[key: string]: IControllerInstance}; Object.keys(requiredControllersMap).forEach((key) => { controllerInstance[key] = requiredControllersMap[key]; }); } return requiredControllers; } private compileHtml(html: string | TrustedHTML): ILinkFn { this.element.innerHTML = html; return this.$compile(this.element.childNodes); } private extractChildNodes(): Node[] { const childNodes: Node[] = []; let childNode: Node | null; while ((childNode = this.element.firstChild)) { (childNode as Element | Comment | Text).remove(); childNodes.push(childNode); } return childNodes; } private getDirectiveRequire(): DirectiveRequireProperty { const require = this.directive.require || (this.directive.controller && this.directive.name)!; if (isMap(require)) { Object.entries(require).forEach(([key, value]) => { const match = value.match(REQUIRE_PREFIX_RE)!; const name = value.substring(match[0].length); if (!name) { require[key] = match[0] + key; } }); } return require; }
{ "end_byte": 10226, "start_byte": 1266, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/upgrade_helper.ts" }
angular/packages/upgrade/src/common/src/upgrade_helper.ts_10230_12074
private resolveRequire( require: DirectiveRequireProperty, ): SingleOrListOrMap<IControllerInstance> | null { if (!require) { return null; } else if (Array.isArray(require)) { return require.map((req) => this.resolveRequire(req)); } else if (typeof require === 'object') { const value: {[key: string]: IControllerInstance} = {}; Object.keys(require).forEach((key) => (value[key] = this.resolveRequire(require[key])!)); return value; } else if (typeof require === 'string') { const match = require.match(REQUIRE_PREFIX_RE)!; const inheritType = match[1] || match[3]; const name = require.substring(match[0].length); const isOptional = !!match[2]; const searchParents = !!inheritType; const startOnParent = inheritType === '^^'; const ctrlKey = controllerKey(name); const elem = startOnParent ? this.$element.parent!() : this.$element; const value = searchParents ? elem.inheritedData!(ctrlKey) : elem.data!(ctrlKey); if (!value && !isOptional) { throw new Error( `Unable to find required '${require}' in upgraded directive '${this.name}'.`, ); } return value; } else { throw new Error( `Unrecognized 'require' syntax on upgraded directive '${this.name}': ${require}`, ); } } } function getOrCall<T>(property: T | Function, ...args: any[]): T { return isFunction(property) ? property(...args) : property; } // NOTE: Only works for `typeof T !== 'object'`. function isMap<T>(value: SingleOrListOrMap<T>): value is {[key: string]: T} { return value && !Array.isArray(value) && typeof value === 'object'; } function notSupported(name: string, feature: string) { throw new Error(`Upgraded directive '${name}' contains unsupported feature: '${feature}'.`); }
{ "end_byte": 12074, "start_byte": 10230, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/upgrade_helper.ts" }
angular/packages/upgrade/src/common/src/constants.ts_0_1404
/** * @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 const $COMPILE = '$compile'; export const $CONTROLLER = '$controller'; export const $DELEGATE = '$delegate'; export const $EXCEPTION_HANDLER = '$exceptionHandler'; export const $HTTP_BACKEND = '$httpBackend'; export const $INJECTOR = '$injector'; export const $INTERVAL = '$interval'; export const $PARSE = '$parse'; export const $PROVIDE = '$provide'; export const $ROOT_ELEMENT = '$rootElement'; export const $ROOT_SCOPE = '$rootScope'; export const $SCOPE = '$scope'; export const $TEMPLATE_CACHE = '$templateCache'; export const $TEMPLATE_REQUEST = '$templateRequest'; export const $$TESTABILITY = '$$testability'; export const COMPILER_KEY = '$$angularCompiler'; export const DOWNGRADED_MODULE_COUNT_KEY = '$$angularDowngradedModuleCount'; export const GROUP_PROJECTABLE_NODES_KEY = '$$angularGroupProjectableNodes'; export const INJECTOR_KEY = '$$angularInjector'; export const LAZY_MODULE_REF = '$$angularLazyModuleRef'; export const NG_ZONE_KEY = '$$angularNgZone'; export const UPGRADE_APP_TYPE_KEY = '$$angularUpgradeAppType'; export const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY; export const REQUIRE_NG_MODEL = '?ngModel'; export const UPGRADE_MODULE_NAME = '$$UpgradeModule';
{ "end_byte": 1404, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/constants.ts" }
angular/packages/upgrade/src/common/src/downgrade_component.ts_0_3204
/** * @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 {ComponentFactory, ComponentFactoryResolver, Injector, NgZone, Type} from '@angular/core'; import { IAnnotatedFunction, IAttributes, IAugmentedJQuery, ICompileService, IDirective, IInjectorService, INgModelController, IParseService, IScope, } from './angular1'; import { $COMPILE, $INJECTOR, $PARSE, INJECTOR_KEY, LAZY_MODULE_REF, REQUIRE_INJECTOR, REQUIRE_NG_MODEL, } from './constants'; import {DowngradeComponentAdapter} from './downgrade_component_adapter'; import {SyncPromise, Thenable} from './promise_util'; import { controllerKey, getDowngradedModuleCount, getTypeName, getUpgradeAppType, LazyModuleRef, UpgradeAppType, validateInjectionKey, } from './util'; /** * @description * * A helper function that allows an Angular component to be used from AngularJS. * * *Part of the [upgrade/static](api?query=upgrade%2Fstatic) * library for hybrid upgrade apps that support AOT compilation* * * This helper function returns a factory function to be used for registering * an AngularJS wrapper directive for "downgrading" an Angular component. * * @usageNotes * ### Examples * * Let's assume that you have an Angular component called `ng2Heroes` that needs * to be made available in AngularJS templates. * * {@example upgrade/static/ts/full/module.ts region="ng2-heroes"} * * We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive) * that will make this Angular component available inside AngularJS templates. * The `downgradeComponent()` function returns a factory function that we * can use to define the AngularJS directive that wraps the "downgraded" component. * * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-wrapper"} * * For more details and examples on downgrading Angular components to AngularJS components please * visit the [Upgrade guide](https://angular.io/guide/upgrade#using-angular-components-from-angularjs-code). * * @param info contains information about the Component that is being downgraded: * * - `component: Type<any>`: The type of the Component that will be downgraded * - `downgradedModule?: string`: The name of the downgraded module (if any) that the component * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose * corresponding Angular module will be bootstrapped, when the component needs to be instantiated. * <br /> * (This option is only necessary when using `downgradeModule()` to downgrade more than one * Angular module.) * - `propagateDigest?: boolean`: Whether to perform {@link ChangeDetectorRef#detectChanges} on the * component on every * [$digest](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest). If set to `false`, * change detection will still be performed when any of the component's inputs changes. * (Default: true) * * @returns a factory function that can be used to register the component in an * AngularJS module. * * @publicApi */
{ "end_byte": 3204, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/downgrade_component.ts" }
angular/packages/upgrade/src/common/src/downgrade_component.ts_3205_12100
export function downgradeComponent(info: { component: Type<any>; downgradedModule?: string; propagateDigest?: boolean; /** @deprecated since v4. This parameter is no longer used */ inputs?: string[]; /** @deprecated since v4. This parameter is no longer used */ outputs?: string[]; /** @deprecated since v4. This parameter is no longer used */ selectors?: string[]; }): any /* angular.IInjectable */ { const directiveFactory: IAnnotatedFunction = function ( $compile: ICompileService, $injector: IInjectorService, $parse: IParseService, ): IDirective { const unsafelyOverwriteSignalInputs = (info as {unsafelyOverwriteSignalInputs?: boolean}).unsafelyOverwriteSignalInputs ?? false; // When using `downgradeModule()`, we need to handle certain things specially. For example: // - We always need to attach the component view to the `ApplicationRef` for it to be // dirty-checked. // - We need to ensure callbacks to Angular APIs (e.g. change detection) are run inside the // Angular zone. // NOTE: This is not needed, when using `UpgradeModule`, because `$digest()` will be run // inside the Angular zone (except if explicitly escaped, in which case we shouldn't // force it back in). const isNgUpgradeLite = getUpgradeAppType($injector) === UpgradeAppType.Lite; const wrapCallback: <T>(cb: () => T) => typeof cb = !isNgUpgradeLite ? (cb) => cb : (cb) => () => (NgZone.isInAngularZone() ? cb() : ngZone.run(cb)); let ngZone: NgZone; // When downgrading multiple modules, special handling is needed wrt injectors. const hasMultipleDowngradedModules = isNgUpgradeLite && getDowngradedModuleCount($injector) > 1; return { restrict: 'E', terminal: true, require: [REQUIRE_INJECTOR, REQUIRE_NG_MODEL], // Controller needs to be set so that `angular-component-router.js` (from beta Angular 2) // configuration properties can be made available. See: // See G3: javascript/angular2/angular1_router_lib.js // https://github.com/angular/angular.js/blob/47bf11ee94664367a26ed8c91b9b586d3dd420f5/src/ng/compile.js#L1670-L1691. controller: function () {}, link: (scope: IScope, element: IAugmentedJQuery, attrs: IAttributes, required: any[]) => { // We might have to compile the contents asynchronously, because this might have been // triggered by `UpgradeNg1ComponentAdapterBuilder`, before the Angular templates have // been compiled. const ngModel: INgModelController = required[1]; const parentInjector: Injector | Thenable<Injector> | undefined = required[0]; let moduleInjector: Injector | Thenable<Injector> | undefined = undefined; let ranAsync = false; if (!parentInjector || hasMultipleDowngradedModules) { const downgradedModule = info.downgradedModule || ''; const lazyModuleRefKey = `${LAZY_MODULE_REF}${downgradedModule}`; const attemptedAction = `instantiating component '${getTypeName(info.component)}'`; validateInjectionKey($injector, downgradedModule, lazyModuleRefKey, attemptedAction); const lazyModuleRef = $injector.get(lazyModuleRefKey) as LazyModuleRef; moduleInjector = lazyModuleRef.injector ?? lazyModuleRef.promise; } // Notes: // // There are two injectors: `finalModuleInjector` and `finalParentInjector` (they might be // the same instance, but that is irrelevant): // - `finalModuleInjector` is used to retrieve `ComponentFactoryResolver`, thus it must be // on the same tree as the `NgModule` that declares this downgraded component. // - `finalParentInjector` is used for all other injection purposes. // (Note that Angular knows to only traverse the component-tree part of that injector, // when looking for an injectable and then switch to the module injector.) // // There are basically three cases: // - If there is no parent component (thus no `parentInjector`), we bootstrap the downgraded // `NgModule` and use its injector as both `finalModuleInjector` and // `finalParentInjector`. // - If there is a parent component (and thus a `parentInjector`) and we are sure that it // belongs to the same `NgModule` as this downgraded component (e.g. because there is only // one downgraded module, we use that `parentInjector` as both `finalModuleInjector` and // `finalParentInjector`. // - If there is a parent component, but it may belong to a different `NgModule`, then we // use the `parentInjector` as `finalParentInjector` and this downgraded component's // declaring `NgModule`'s injector as `finalModuleInjector`. // Note 1: If the `NgModule` is already bootstrapped, we just get its injector (we don't // bootstrap again). // Note 2: It is possible that (while there are multiple downgraded modules) this // downgraded component and its parent component both belong to the same NgModule. // In that case, we could have used the `parentInjector` as both // `finalModuleInjector` and `finalParentInjector`, but (for simplicity) we are // treating this case as if they belong to different `NgModule`s. That doesn't // really affect anything, since `parentInjector` has `moduleInjector` as ancestor // and trying to resolve `ComponentFactoryResolver` from either one will return // the same instance. // If there is a parent component, use its injector as parent injector. // If this is a "top-level" Angular component, use the module injector. const finalParentInjector = parentInjector || moduleInjector!; // If this is a "top-level" Angular component or the parent component may belong to a // different `NgModule`, use the module injector for module-specific dependencies. // If there is a parent component that belongs to the same `NgModule`, use its injector. const finalModuleInjector = moduleInjector || parentInjector!; const doDowngrade = (injector: Injector, moduleInjector: Injector) => { // Retrieve `ComponentFactoryResolver` from the injector tied to the `NgModule` this // component belongs to. const componentFactoryResolver: ComponentFactoryResolver = moduleInjector.get(ComponentFactoryResolver); const componentFactory: ComponentFactory<any> = componentFactoryResolver.resolveComponentFactory(info.component)!; if (!componentFactory) { throw new Error(`Expecting ComponentFactory for: ${getTypeName(info.component)}`); } const injectorPromise = new ParentInjectorPromise(element); const facade = new DowngradeComponentAdapter( element, attrs, scope, ngModel, injector, $compile, $parse, componentFactory, wrapCallback, unsafelyOverwriteSignalInputs, ); const projectableNodes = facade.compileContents(); const componentRef = facade.createComponentAndSetup( projectableNodes, isNgUpgradeLite, info.propagateDigest, ); injectorPromise.resolve(componentRef.injector); if (ranAsync) { // If this is run async, it is possible that it is not run inside a // digest and initial input values will not be detected. scope.$evalAsync(() => {}); } }; const downgradeFn = !isNgUpgradeLite ? doDowngrade : (pInjector: Injector, mInjector: Injector) => { if (!ngZone) { ngZone = pInjector.get(NgZone); } wrapCallback(() => doDowngrade(pInjector, mInjector))(); }; // NOTE: // Not using `ParentInjectorPromise.all()` (which is inherited from `SyncPromise`), because // Closure Compiler (or some related tool) complains: // `TypeError: ...$src$downgrade_component_ParentInjectorPromise.all is not a function` SyncPromise.all([finalParentInjector, finalModuleInjector]).then(([pInjector, mInjector]) => downgradeFn(pInjector, mInjector), ); ranAsync = true; }, }; }; // bracket-notation because of closure - see #14441 directiveFactory['$inject'] = [$COMPILE, $INJECTOR, $PARSE]; return directiveFactory; } /** * Synchronous promise-like object to wrap parent injectors, * to preserve the synchronous nature of AngularJS's `$compile`. */
{ "end_byte": 12100, "start_byte": 3205, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/downgrade_component.ts" }
angular/packages/upgrade/src/common/src/downgrade_component.ts_12101_12665
class ParentInjectorPromise extends SyncPromise<Injector> { private injectorKey: string = controllerKey(INJECTOR_KEY); constructor(private element: IAugmentedJQuery) { super(); // Store the promise on the element. element.data!(this.injectorKey, this); } override resolve(injector: Injector): void { // Store the real injector on the element. this.element.data!(this.injectorKey, injector); // Release the element to prevent memory leaks. this.element = null!; // Resolve the promise. super.resolve(injector); } }
{ "end_byte": 12665, "start_byte": 12101, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/downgrade_component.ts" }
angular/packages/upgrade/src/common/src/util.ts_0_7230
/** * @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 {Injector, Type, ɵNG_MOD_DEF} from '@angular/core'; import { element as angularElement, IAugmentedJQuery, IInjectorService, INgModelController, IRootScopeService, } from './angular1'; import { $ROOT_ELEMENT, $ROOT_SCOPE, DOWNGRADED_MODULE_COUNT_KEY, UPGRADE_APP_TYPE_KEY, } from './constants'; const DIRECTIVE_PREFIX_REGEXP = /^(?:x|data)[:\-_]/i; const DIRECTIVE_SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g; export function onError(e: any) { // TODO: (misko): We seem to not have a stack trace here! console.error(e, e.stack); throw e; } /** * Clean the jqLite/jQuery data on the element and all its descendants. * Equivalent to how jqLite/jQuery invoke `cleanData()` on an Element when removed: * https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/jqLite.js#L349-L355 * https://github.com/jquery/jquery/blob/6984d1747623dbc5e87fd6c261a5b6b1628c107c/src/manipulation.js#L182 * * NOTE: * `cleanData()` will also invoke the AngularJS `$destroy` DOM event on the element: * https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/Angular.js#L1932-L1945 * * @param node The DOM node whose data needs to be cleaned. */ export function cleanData(node: Node): void { angularElement.cleanData([node]); if (isParentNode(node)) { angularElement.cleanData(node.querySelectorAll('*')); } } export function controllerKey(name: string): string { return '$' + name + 'Controller'; } /** * Destroy an AngularJS app given the app `$injector`. * * NOTE: Destroying an app is not officially supported by AngularJS, but try to do our best by * destroying `$rootScope` and clean the jqLite/jQuery data on `$rootElement` and all * descendants. * * @param $injector The `$injector` of the AngularJS app to destroy. */ export function destroyApp($injector: IInjectorService): void { const $rootElement: IAugmentedJQuery = $injector.get($ROOT_ELEMENT); const $rootScope: IRootScopeService = $injector.get($ROOT_SCOPE); $rootScope.$destroy(); cleanData($rootElement[0]); } export function directiveNormalize(name: string): string { return name .replace(DIRECTIVE_PREFIX_REGEXP, '') .replace(DIRECTIVE_SPECIAL_CHARS_REGEXP, (_, letter) => letter.toUpperCase()); } export function getTypeName(type: Type<any>): string { // Return the name of the type or the first line of its stringified version. return (type as any).overriddenName || type.name || type.toString().split('\n')[0]; } export function getDowngradedModuleCount($injector: IInjectorService): number { return $injector.has(DOWNGRADED_MODULE_COUNT_KEY) ? $injector.get(DOWNGRADED_MODULE_COUNT_KEY) : 0; } export function getUpgradeAppType($injector: IInjectorService): UpgradeAppType { return $injector.has(UPGRADE_APP_TYPE_KEY) ? $injector.get(UPGRADE_APP_TYPE_KEY) : UpgradeAppType.None; } export function isFunction(value: any): value is Function { return typeof value === 'function'; } export function isNgModuleType(value: any): value is Type<unknown> { // NgModule class should have the `ɵmod` static property attached by AOT or JIT compiler. return isFunction(value) && !!value[ɵNG_MOD_DEF]; } function isParentNode(node: Node | ParentNode): node is ParentNode { return isFunction((node as unknown as ParentNode).querySelectorAll); } export function validateInjectionKey( $injector: IInjectorService, downgradedModule: string, injectionKey: string, attemptedAction: string, ): void { const upgradeAppType = getUpgradeAppType($injector); const downgradedModuleCount = getDowngradedModuleCount($injector); // Check for common errors. switch (upgradeAppType) { case UpgradeAppType.Dynamic: case UpgradeAppType.Static: if (downgradedModule) { throw new Error( `Error while ${attemptedAction}: 'downgradedModule' unexpectedly specified.\n` + "You should not specify a value for 'downgradedModule', unless you are downgrading " + "more than one Angular module (via 'downgradeModule()').", ); } break; case UpgradeAppType.Lite: if (!downgradedModule && downgradedModuleCount >= 2) { throw new Error( `Error while ${attemptedAction}: 'downgradedModule' not specified.\n` + 'This application contains more than one downgraded Angular module, thus you need to ' + "always specify 'downgradedModule' when downgrading components and injectables.", ); } if (!$injector.has(injectionKey)) { throw new Error( `Error while ${attemptedAction}: Unable to find the specified downgraded module.\n` + 'Did you forget to downgrade an Angular module or include it in the AngularJS ' + 'application?', ); } break; default: throw new Error( `Error while ${attemptedAction}: Not a valid '@angular/upgrade' application.\n` + 'Did you forget to downgrade an Angular module or include it in the AngularJS ' + 'application?', ); } } export class Deferred<R> { promise: Promise<R>; resolve!: (value: R | PromiseLike<R>) => void; reject!: (error?: any) => void; constructor() { this.promise = new Promise((res, rej) => { this.resolve = res; this.reject = rej; }); } } export interface LazyModuleRef { injector?: Injector; promise?: Promise<Injector>; } export const enum UpgradeAppType { // App NOT using `@angular/upgrade`. (This should never happen in an `ngUpgrade` app.) None, // App using the deprecated `@angular/upgrade` APIs (a.k.a. dynamic `ngUpgrade`). Dynamic, // App using `@angular/upgrade/static` with `UpgradeModule`. Static, // App using @angular/upgrade/static` with `downgradeModule()` (a.k.a `ngUpgrade`-lite ). Lite, } /** * @return Whether the passed-in component implements the subset of the * `ControlValueAccessor` interface needed for AngularJS `ng-model` * compatibility. */ function supportsNgModel(component: any) { return ( typeof component.writeValue === 'function' && typeof component.registerOnChange === 'function' ); } /** * Glue the AngularJS `NgModelController` (if it exists) to the component * (if it implements the needed subset of the `ControlValueAccessor` interface). */ export function hookupNgModel(ngModel: INgModelController, component: any) { if (ngModel && supportsNgModel(component)) { ngModel.$render = () => { component.writeValue(ngModel.$viewValue); }; component.registerOnChange(ngModel.$setViewValue.bind(ngModel)); if (typeof component.registerOnTouched === 'function') { component.registerOnTouched(ngModel.$setTouched.bind(ngModel)); } } } /** * Test two values for strict equality, accounting for the fact that `NaN !== NaN`. */ export function strictEquals(val1: any, val2: any): boolean { return val1 === val2 || (val1 !== val1 && val2 !== val2); }
{ "end_byte": 7230, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/util.ts" }
angular/packages/upgrade/src/common/src/component_info.ts_0_1026
/** * @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 */ /** * A `PropertyBinding` represents a mapping between a property name * and an attribute name. It is parsed from a string of the form * `"prop: attr"`; or simply `"propAndAttr" where the property * and attribute have the same identifier. */ export class PropertyBinding { bracketAttr: string; bracketParenAttr: string; parenAttr: string; onAttr: string; bindAttr: string; bindonAttr: string; constructor( public prop: string, public attr: string, ) { this.bracketAttr = `[${this.attr}]`; this.parenAttr = `(${this.attr})`; this.bracketParenAttr = `[(${this.attr})]`; const capitalAttr = this.attr.charAt(0).toUpperCase() + this.attr.slice(1); this.onAttr = `on${capitalAttr}`; this.bindAttr = `bind${capitalAttr}`; this.bindonAttr = `bindon${capitalAttr}`; } }
{ "end_byte": 1026, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/component_info.ts" }
angular/packages/upgrade/src/common/src/version.ts_0_418
/** * @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 */ /** * @module * @description * Entry point for all public APIs of the upgrade package. */ import {Version} from '@angular/core'; /** * @publicApi */ export const VERSION = new Version('0.0.0-PLACEHOLDER');
{ "end_byte": 418, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/version.ts" }
angular/packages/upgrade/src/common/src/downgrade_component_adapter.ts_0_859
/** * @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, ChangeDetectorRef, ComponentFactory, ComponentRef, EventEmitter, Injector, OnChanges, SimpleChange, SimpleChanges, StaticProvider, Testability, TestabilityRegistry, type ɵInputSignalNode as InputSignalNode, ɵSIGNAL as SIGNAL, } from '@angular/core'; import { IAttributes, IAugmentedJQuery, ICompileService, INgModelController, IParseService, IScope, } from './angular1'; import {PropertyBinding} from './component_info'; import {$SCOPE} from './constants'; import {cleanData, getTypeName, hookupNgModel, strictEquals} from './util'; const INITIAL_VALUE = { __UNINITIALIZED__: true, };
{ "end_byte": 859, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/downgrade_component_adapter.ts" }
angular/packages/upgrade/src/common/src/downgrade_component_adapter.ts_861_9646
port class DowngradeComponentAdapter { private implementsOnChanges = false; private inputChangeCount: number = 0; private inputChanges: SimpleChanges = {}; private componentScope: IScope; constructor( private element: IAugmentedJQuery, private attrs: IAttributes, private scope: IScope, private ngModel: INgModelController, private parentInjector: Injector, private $compile: ICompileService, private $parse: IParseService, private componentFactory: ComponentFactory<any>, private wrapCallback: <T>(cb: () => T) => () => T, private readonly unsafelyOverwriteSignalInputs: boolean, ) { this.componentScope = scope.$new(); } compileContents(): Node[][] { const compiledProjectableNodes: Node[][] = []; const projectableNodes: Node[][] = this.groupProjectableNodes(); const linkFns = projectableNodes.map((nodes) => this.$compile(nodes)); this.element.empty!(); linkFns.forEach((linkFn) => { linkFn(this.scope, (clone: Node[]) => { compiledProjectableNodes.push(clone); this.element.append!(clone); }); }); return compiledProjectableNodes; } createComponentAndSetup( projectableNodes: Node[][], manuallyAttachView = false, propagateDigest = true, ): ComponentRef<any> { const component = this.createComponent(projectableNodes); this.setupInputs(manuallyAttachView, propagateDigest, component); this.setupOutputs(component.componentRef); this.registerCleanup(component.componentRef); return component.componentRef; } private createComponent(projectableNodes: Node[][]): ComponentInfo { const providers: StaticProvider[] = [{provide: $SCOPE, useValue: this.componentScope}]; const childInjector = Injector.create({ providers: providers, parent: this.parentInjector, name: 'DowngradeComponentAdapter', }); const componentRef = this.componentFactory.create( childInjector, projectableNodes, this.element[0], ); const viewChangeDetector = componentRef.injector.get(ChangeDetectorRef); const changeDetector = componentRef.changeDetectorRef; // testability hook is commonly added during component bootstrap in // packages/core/src/application_ref.bootstrap() // in downgraded application, component creation will take place here as well as adding the // testability hook. const testability = componentRef.injector.get(Testability, null); if (testability) { componentRef.injector .get(TestabilityRegistry) .registerApplication(componentRef.location.nativeElement, testability); } hookupNgModel(this.ngModel, componentRef.instance); return {viewChangeDetector, componentRef, changeDetector}; } private setupInputs( manuallyAttachView: boolean, propagateDigest = true, {componentRef, changeDetector, viewChangeDetector}: ComponentInfo, ): void { const attrs = this.attrs; const inputs = this.componentFactory.inputs || []; for (const input of inputs) { const inputBinding = new PropertyBinding(input.propName, input.templateName); let expr: string | null = null; if (attrs.hasOwnProperty(inputBinding.attr)) { const observeFn = ((prop, isSignal) => { let prevValue = INITIAL_VALUE; return (currValue: any) => { // Initially, both `$observe()` and `$watch()` will call this function. if (!strictEquals(prevValue, currValue)) { if (prevValue === INITIAL_VALUE) { prevValue = currValue; } this.updateInput(componentRef, prop, prevValue, currValue, isSignal); prevValue = currValue; } }; })(inputBinding.prop, input.isSignal); attrs.$observe(inputBinding.attr, observeFn); // Use `$watch()` (in addition to `$observe()`) in order to initialize the input in time // for `ngOnChanges()`. This is necessary if we are already in a `$digest`, which means that // `ngOnChanges()` (which is called by a watcher) will run before the `$observe()` callback. let unwatch: Function | null = this.componentScope.$watch(() => { unwatch!(); unwatch = null; observeFn(attrs[inputBinding.attr]); }); } else if (attrs.hasOwnProperty(inputBinding.bindAttr)) { expr = attrs[inputBinding.bindAttr]; } else if (attrs.hasOwnProperty(inputBinding.bracketAttr)) { expr = attrs[inputBinding.bracketAttr]; } else if (attrs.hasOwnProperty(inputBinding.bindonAttr)) { expr = attrs[inputBinding.bindonAttr]; } else if (attrs.hasOwnProperty(inputBinding.bracketParenAttr)) { expr = attrs[inputBinding.bracketParenAttr]; } if (expr != null) { const watchFn = ( (prop, isSignal) => (currValue: unknown, prevValue: unknown) => this.updateInput(componentRef, prop, prevValue, currValue, isSignal) )(inputBinding.prop, input.isSignal); this.componentScope.$watch(expr, watchFn); } } // Invoke `ngOnChanges()` and Change Detection (when necessary) const detectChanges = () => changeDetector.detectChanges(); const prototype = this.componentFactory.componentType.prototype; this.implementsOnChanges = !!(prototype && (<OnChanges>prototype).ngOnChanges); this.componentScope.$watch( () => this.inputChangeCount, this.wrapCallback(() => { // Invoke `ngOnChanges()` if (this.implementsOnChanges) { const inputChanges = this.inputChanges; this.inputChanges = {}; (<OnChanges>componentRef.instance).ngOnChanges(inputChanges); } viewChangeDetector.markForCheck(); // If opted out of propagating digests, invoke change detection when inputs change. if (!propagateDigest) { detectChanges(); } }), ); // If not opted out of propagating digests, invoke change detection on every digest if (propagateDigest) { this.componentScope.$watch(this.wrapCallback(detectChanges)); } // If necessary, attach the view so that it will be dirty-checked. // (Allow time for the initial input values to be set and `ngOnChanges()` to be called.) if (manuallyAttachView || !propagateDigest) { let unwatch: Function | null = this.componentScope.$watch(() => { unwatch!(); unwatch = null; const appRef = this.parentInjector.get<ApplicationRef>(ApplicationRef); appRef.attachView(componentRef.hostView); }); } } private setupOutputs(componentRef: ComponentRef<any>) { const attrs = this.attrs; const outputs = this.componentFactory.outputs || []; for (const output of outputs) { const outputBindings = new PropertyBinding(output.propName, output.templateName); const bindonAttr = outputBindings.bindonAttr.substring( 0, outputBindings.bindonAttr.length - 6, ); const bracketParenAttr = `[(${outputBindings.bracketParenAttr.substring( 2, outputBindings.bracketParenAttr.length - 8, )})]`; // order below is important - first update bindings then evaluate expressions if (attrs.hasOwnProperty(bindonAttr)) { this.subscribeToOutput(componentRef, outputBindings, attrs[bindonAttr], true); } if (attrs.hasOwnProperty(bracketParenAttr)) { this.subscribeToOutput(componentRef, outputBindings, attrs[bracketParenAttr], true); } if (attrs.hasOwnProperty(outputBindings.onAttr)) { this.subscribeToOutput(componentRef, outputBindings, attrs[outputBindings.onAttr]); } if (attrs.hasOwnProperty(outputBindings.parenAttr)) { this.subscribeToOutput(componentRef, outputBindings, attrs[outputBindings.parenAttr]); } } } private subscribeToOutput( componentRef: ComponentRef<any>, output: PropertyBinding, expr: string, isAssignment: boolean = false, ) { const getter = this.$parse(expr); const setter = getter.assign; if (isAssignment && !setter) { throw new Error(`Expression '${expr}' is not assignable!`); } const emitter = componentRef.instance[output.prop] as EventEmitter<any>; if (emitter) { const subscription = emitter.subscribe({ next: isAssignment ? (v: any) => setter!(this.scope, v) : (v: any) => getter(this.scope, {'$event': v}), }); componentRef.onDestroy(() => subscription.unsubscribe()); } else { throw new Error( `Missing emitter '${output.prop}' on component '${getTypeName( this.componentFactory.componentType, )}'!`, ); } }
{ "end_byte": 9646, "start_byte": 861, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/downgrade_component_adapter.ts" }
angular/packages/upgrade/src/common/src/downgrade_component_adapter.ts_9650_14122
ivate registerCleanup(componentRef: ComponentRef<any>) { const testabilityRegistry = componentRef.injector.get(TestabilityRegistry); const destroyComponentRef = this.wrapCallback(() => componentRef.destroy()); let destroyed = false; this.element.on!('$destroy', () => { // The `$destroy` event may have been triggered by the `cleanData()` call in the // `componentScope` `$destroy` handler below. In that case, we don't want to call // `componentScope.$destroy()` again. if (!destroyed) this.componentScope.$destroy(); }); this.componentScope.$on('$destroy', () => { if (!destroyed) { destroyed = true; testabilityRegistry.unregisterApplication(componentRef.location.nativeElement); // The `componentScope` might be getting destroyed, because an ancestor element is being // removed/destroyed. If that is the case, jqLite/jQuery would normally invoke `cleanData()` // on the removed element and all descendants. // https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/jqLite.js#L349-L355 // https://github.com/jquery/jquery/blob/6984d1747623dbc5e87fd6c261a5b6b1628c107c/src/manipulation.js#L182 // // Here, however, `destroyComponentRef()` may under some circumstances remove the element // from the DOM and therefore it will no longer be a descendant of the removed element when // `cleanData()` is called. This would result in a memory leak, because the element's data // and event handlers (and all objects directly or indirectly referenced by them) would be // retained. // // To ensure the element is always properly cleaned up, we manually call `cleanData()` on // this element and its descendants before destroying the `ComponentRef`. cleanData(this.element[0]); destroyComponentRef(); } }); } private updateInput( componentRef: ComponentRef<any>, prop: string, prevValue: any, currValue: any, isSignal: boolean, ) { if (this.implementsOnChanges) { this.inputChanges[prop] = new SimpleChange(prevValue, currValue, prevValue === currValue); } this.inputChangeCount++; if (isSignal && !this.unsafelyOverwriteSignalInputs) { const node = componentRef.instance[prop][SIGNAL] as InputSignalNode<unknown, unknown>; node.applyValueToInputSignal(node, currValue); } else { componentRef.instance[prop] = currValue; } } private groupProjectableNodes() { let ngContentSelectors = this.componentFactory.ngContentSelectors; return groupNodesBySelector(ngContentSelectors, this.element.contents!()); } } /** * Group a set of DOM nodes into `ngContent` groups, based on the given content selectors. */ export function groupNodesBySelector(ngContentSelectors: string[], nodes: Node[]): Node[][] { const projectableNodes: Node[][] = []; for (let i = 0, ii = ngContentSelectors.length; i < ii; ++i) { projectableNodes[i] = []; } for (let j = 0, jj = nodes.length; j < jj; ++j) { const node = nodes[j]; const ngContentIndex = findMatchingNgContentIndex(node, ngContentSelectors); if (ngContentIndex != null) { projectableNodes[ngContentIndex].push(node); } } return projectableNodes; } function findMatchingNgContentIndex(element: any, ngContentSelectors: string[]): number | null { const ngContentIndices: number[] = []; let wildcardNgContentIndex: number = -1; for (let i = 0; i < ngContentSelectors.length; i++) { const selector = ngContentSelectors[i]; if (selector === '*') { wildcardNgContentIndex = i; } else { if (matchesSelector(element, selector)) { ngContentIndices.push(i); } } } ngContentIndices.sort(); if (wildcardNgContentIndex !== -1) { ngContentIndices.push(wildcardNgContentIndex); } return ngContentIndices.length ? ngContentIndices[0] : null; } function matchesSelector(el: any, selector: string): boolean { const elProto = <any>Element.prototype; return el.nodeType === Node.ELEMENT_NODE ? // matches is supported by all browsers from 2014 onwards except non-chromium edge (elProto.matches ?? elProto.msMatchesSelector).call(el, selector) : false; } interface ComponentInfo { componentRef: ComponentRef<any>; changeDetector: ChangeDetectorRef; viewChangeDetector: ChangeDetectorRef; }
{ "end_byte": 14122, "start_byte": 9650, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/downgrade_component_adapter.ts" }
angular/packages/upgrade/src/common/src/security/trusted_types.ts_0_2356
/** * @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 */ /** * @fileoverview * A module to facilitate use of a Trusted Types policy internally within * the upgrade package. It lazily constructs the Trusted Types policy, providing * helper utilities for promoting strings to Trusted Types. When Trusted Types * are not available, strings are used as a fallback. * @security All use of this module is security-sensitive and should go through * security review. */ import {TrustedHTML, TrustedTypePolicy, TrustedTypePolicyFactory} from './trusted_types_defs'; /** * The Trusted Types policy, or null if Trusted Types are not * enabled/supported, or undefined if the policy has not been created yet. */ let policy: TrustedTypePolicy | null | undefined; /** * Returns the Trusted Types policy, or null if Trusted Types are not * enabled/supported. The first call to this function will create the policy. */ function getPolicy(): TrustedTypePolicy | null { if (policy === undefined) { policy = null; const windowWithTrustedTypes = window as unknown as {trustedTypes?: TrustedTypePolicyFactory}; if (windowWithTrustedTypes.trustedTypes) { try { policy = windowWithTrustedTypes.trustedTypes.createPolicy('angular#unsafe-upgrade', { createHTML: (s: string) => s, }); } catch { // trustedTypes.createPolicy throws if called with a name that is // already registered, even in report-only mode. Until the API changes, // catch the error not to break the applications functionally. In such // cases, the code will fall back to using strings. } } } return policy; } /** * Unsafely promote a legacy AngularJS template to a TrustedHTML, falling back * to strings when Trusted Types are not available. * @security This is a security-sensitive function; any use of this function * must go through security review. In particular, the template string should * always be under full control of the application author, as untrusted input * can cause an XSS vulnerability. */ export function trustedHTMLFromLegacyTemplate(html: string): TrustedHTML | string { return getPolicy()?.createHTML(html) || html; }
{ "end_byte": 2356, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/security/trusted_types.ts" }
angular/packages/upgrade/src/common/src/security/trusted_types_defs.ts_0_1519
/** * @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 */ /** * @fileoverview * While Angular only uses Trusted Types internally for the time being, * references to Trusted Types could leak into our public API, which would force * anyone compiling against @angular/upgrade to provide the @types/trusted-types * package in their compilation unit. * * Until https://github.com/microsoft/TypeScript/issues/30024 is resolved, we * will keep Angular's public API surface free of references to Trusted Types. * For internal and semi-private APIs that need to reference Trusted Types, the * minimal type definitions for the Trusted Types API provided by this module * should be used instead. They are marked as "declare" to prevent them from * being renamed by compiler optimization. * * Adapted from * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/trusted-types/index.d.ts * but restricted to the API surface used within Angular, mimicking the approach * in packages/core/src/util/security/trusted_type_defs.ts. */ export type TrustedHTML = string & { __brand__: 'TrustedHTML'; }; export interface TrustedTypePolicyFactory { createPolicy( policyName: string, policyOptions: {createHTML?: (input: string) => string}, ): TrustedTypePolicy; } export interface TrustedTypePolicy { createHTML(input: string): TrustedHTML; }
{ "end_byte": 1519, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/upgrade/src/common/src/security/trusted_types_defs.ts" }
angular/packages/forms/PACKAGE.md_0_1287
Implements a set of directives and providers to communicate with native DOM elements when building forms to capture user input. Use this API to register directives, build form and data models, and provide validation to your forms. Validators can be synchronous or asynchronous depending on your use case. You can also extend the built-in functionality provided by forms in Angular by using the interfaces and tokens to create custom validators and input elements. Angular forms allow you to: * Capture the current value and validation status of a form. * Track and listen for changes to the form's data model. * Validate the correctness of user input. * Create custom validators and input elements. You can build forms in one of two ways: * *Reactive forms* use existing instances of a `FormControl` or `FormGroup` to build a form model. This form model is synced with form input elements through directives to track and communicate changes back to the form model. Changes to the value and status of the controls are provided as observables. * *Template-driven forms* rely on directives such as `NgModel` and `NgModelGroup` create the form model for you, so any changes to the form are communicated through the template. @see Find out more in the [Forms Overview](guide/forms).
{ "end_byte": 1287, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/PACKAGE.md" }
angular/packages/forms/BUILD.bazel_0_1858
load("//tools:defaults.bzl", "api_golden_test", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package") package(default_visibility = ["//visibility:public"]) ng_module( name = "forms", srcs = glob( [ "*.ts", "src/**/*.ts", ], ), deps = [ "//packages/core", "//packages/platform-browser", "@npm//rxjs", ], ) ng_package( name = "npm_package", package_name = "@angular/forms", srcs = ["package.json"], tags = [ "release-with-framework", ], # Do not add more to this list. # Dependencies on the full npm_package cause long re-builds. visibility = [ "//adev:__pkg__", "//integration:__subpackages__", "//modules/ssr-benchmarks:__pkg__", "//packages/compiler-cli/integrationtest:__pkg__", "//packages/compiler-cli/test/diagnostics:__pkg__", "//packages/language-service/test:__pkg__", ], deps = [ ":forms", ], ) api_golden_test_npm_package( name = "forms_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular/goldens/public-api/forms", npm_package = "angular/packages/forms/npm_package", ) api_golden_test( name = "forms_errors", data = [ "//goldens:public-api", "//packages/forms", ], entry_point = "angular/packages/forms/src/errors.d.ts", golden = "angular/goldens/public-api/forms/errors.api.md", ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "forms_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/forms", )
{ "end_byte": 1858, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/BUILD.bazel" }
angular/packages/forms/index.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 */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/index.ts" }
angular/packages/forms/public_api.ts_0_396
/** * @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 */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/forms'; // This file only reexports content of the `src` folder. Keep it that way.
{ "end_byte": 396, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/public_api.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_0_836
/** * @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 { ChangeDetectionStrategy, ChangeDetectorRef, Component, Directive, EventEmitter, Input, Output, Type, ViewChild, } from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick, waitForAsync} from '@angular/core/testing'; import { AbstractControl, ControlValueAccessor, FormControl, FormGroup, FormsModule, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgControl, NgForm, NgModel, ReactiveFormsModule, Validators, } from '@angular/forms'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {dispatchEvent} from '@angular/platform-browser/testing/src/browser_util';
{ "end_byte": 836, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_838_9862
describe('value accessors', () => { function initTest<T>(component: Type<T>, ...directives: Type<any>[]): ComponentFixture<T> { TestBed.configureTestingModule({ declarations: [component, ...directives], imports: [FormsModule, ReactiveFormsModule], }); return TestBed.createComponent(component); } it('should support <input> without type', () => { TestBed.overrideComponent(FormControlComp, { set: {template: `<input [formControl]="control">`}, }); const fixture = initTest(FormControlComp); const control = new FormControl('old'); fixture.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('old'); input.nativeElement.value = 'new'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(control.value).toEqual('new'); }); it('should support <input type=text>', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('old')}); fixture.componentInstance.form = form; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('old'); input.nativeElement.value = 'new'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(form.value).toEqual({'login': 'new'}); }); it('should ignore the change event for <input type=text>', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('oldValue')}); fixture.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); form.valueChanges.subscribe({ next: (value) => { throw 'Should not happen'; }, }); input.nativeElement.value = 'updatedValue'; dispatchEvent(input.nativeElement, 'change'); }); it('should support <textarea>', () => { TestBed.overrideComponent(FormControlComp, { set: {template: `<textarea [formControl]="control"></textarea>`}, }); const fixture = initTest(FormControlComp); const control = new FormControl('old'); fixture.componentInstance.control = control; fixture.detectChanges(); // model -> view const textarea = fixture.debugElement.query(By.css('textarea')); expect(textarea.nativeElement.value).toEqual('old'); textarea.nativeElement.value = 'new'; dispatchEvent(textarea.nativeElement, 'input'); // view -> model expect(control.value).toEqual('new'); }); it('should support <type=checkbox>', () => { TestBed.overrideComponent(FormControlComp, { set: {template: `<input type="checkbox" [formControl]="control">`}, }); const fixture = initTest(FormControlComp); const control = new FormControl(true); fixture.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.checked).toBe(true); input.nativeElement.checked = false; dispatchEvent(input.nativeElement, 'change'); // view -> model expect(control.value).toBe(false); }); describe('should support <type=number>', () => { it('with basic use case', () => { const fixture = initTest(FormControlNumberInput); const control = new FormControl(10); fixture.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('10'); input.nativeElement.value = '20'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(control.value).toEqual(20); }); it('when value is cleared in the UI', () => { const fixture = initTest(FormControlNumberInput); const control = new FormControl(10, Validators.required); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = ''; dispatchEvent(input.nativeElement, 'input'); expect(control.valid).toBe(false); expect(control.value).toEqual(null); input.nativeElement.value = '0'; dispatchEvent(input.nativeElement, 'input'); expect(control.valid).toBe(true); expect(control.value).toEqual(0); }); it('should ignore the change event', () => { const fixture = initTest(FormControlNumberInput); const control = new FormControl(); fixture.componentInstance.control = control; fixture.detectChanges(); control.valueChanges.subscribe({ next: (value) => { throw 'Input[number] should not react to change event'; }, }); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = '5'; dispatchEvent(input.nativeElement, 'change'); }); it('when value is cleared programmatically', () => { const fixture = initTest(FormControlNumberInput); const control = new FormControl(10); fixture.componentInstance.control = control; fixture.detectChanges(); control.setValue(null); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual(''); }); }); describe('select controls', () => { describe('in reactive forms', () => { it(`should support primitive values`, () => { if (isNode) return; const fixture = initTest(FormControlNameSelect); fixture.detectChanges(); // model -> view const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual('SF'); expect(sfOption.nativeElement.selected).toBe(true); select.nativeElement.value = 'NY'; dispatchEvent(select.nativeElement, 'change'); fixture.detectChanges(); // view -> model expect(sfOption.nativeElement.selected).toBe(false); expect(fixture.componentInstance.form.value).toEqual({'city': 'NY'}); }); it(`should support objects`, () => { if (isNode) return; const fixture = initTest(FormControlSelectNgValue); fixture.detectChanges(); // model -> view const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual('0: Object'); expect(sfOption.nativeElement.selected).toBe(true); }); it('should throw an error if compareWith is not a function', () => { const fixture = initTest(FormControlSelectWithCompareFn); fixture.componentInstance.compareFn = null!; expect(() => fixture.detectChanges()).toThrowError( /compareWith must be a function, but received null/, ); }); it('should compare options using provided compareWith function', () => { if (isNode) return; const fixture = initTest(FormControlSelectWithCompareFn); fixture.detectChanges(); const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual('0: Object'); expect(sfOption.nativeElement.selected).toBe(true); }); it('should support re-assigning the options array with compareWith', () => { if (isNode) return; const fixture = initTest(FormControlSelectWithCompareFn); fixture.detectChanges(); // Option IDs start out as 0 and 1, so setting the select value to "1: Object" // will select the second option (NY). const select = fixture.debugElement.query(By.css('select')); select.nativeElement.value = '1: Object'; dispatchEvent(select.nativeElement, 'change'); fixture.detectChanges(); expect(fixture.componentInstance.form.value).toEqual({city: {id: 2, name: 'NY'}}); fixture.componentInstance.cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'NY'}, ]; fixture.detectChanges(); // Now that the options array has been re-assigned, new option instances will // be created by ngFor. These instances will have different option IDs, subsequent // to the first: 2 and 3. For the second option to stay selected, the select // value will need to have the ID of the current second option: 3. const nyOption = fixture.debugElement.queryAll(By.css('option'))[1]; expect(select.nativeElement.value).toEqual('3: Object'); expect(nyOption.nativeElement.selected).toBe(true); }); });
{ "end_byte": 9862, "start_byte": 838, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_9868_16461
describe('in template-driven forms', () => { it('with option values that are objects', fakeAsync(() => { if (isNode) return; const fixture = initTest(NgModelSelectForm); const comp = fixture.componentInstance; comp.cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}]; comp.selectedCity = comp.cities[1]; fixture.detectChanges(); tick(); const select = fixture.debugElement.query(By.css('select')); const nycOption = fixture.debugElement.queryAll(By.css('option'))[1]; // model -> view expect(select.nativeElement.value).toEqual('1: Object'); expect(nycOption.nativeElement.selected).toBe(true); select.nativeElement.value = '2: Object'; dispatchEvent(select.nativeElement, 'change'); fixture.detectChanges(); tick(); // view -> model expect(comp.selectedCity['name']).toEqual('Buffalo'); })); it('when new options are added', fakeAsync(() => { if (isNode) return; const fixture = initTest(NgModelSelectForm); const comp = fixture.componentInstance; comp.cities = [{'name': 'SF'}, {'name': 'NYC'}]; comp.selectedCity = comp.cities[1]; fixture.detectChanges(); tick(); comp.cities.push({'name': 'Buffalo'}); comp.selectedCity = comp.cities[2]; fixture.detectChanges(); tick(); const select = fixture.debugElement.query(By.css('select')); const buffalo = fixture.debugElement.queryAll(By.css('option'))[2]; expect(select.nativeElement.value).toEqual('2: Object'); expect(buffalo.nativeElement.selected).toBe(true); })); it('when options are removed', fakeAsync(() => { const fixture = initTest(NgModelSelectForm); const comp = fixture.componentInstance; comp.cities = [{'name': 'SF'}, {'name': 'NYC'}]; comp.selectedCity = comp.cities[1]; fixture.detectChanges(); tick(); const select = fixture.debugElement.query(By.css('select')); expect(select.nativeElement.value).toEqual('1: Object'); comp.cities.pop(); fixture.detectChanges(); tick(); expect(select.nativeElement.value).not.toEqual('1: Object'); })); it('when option values have same content, but different identities', fakeAsync(() => { if (isNode) return; const fixture = initTest(NgModelSelectForm); const comp = fixture.componentInstance; comp.cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'NYC'}]; comp.selectedCity = comp.cities[0]; fixture.detectChanges(); comp.selectedCity = comp.cities[2]; fixture.detectChanges(); tick(); const select = fixture.debugElement.query(By.css('select')); const secondNYC = fixture.debugElement.queryAll(By.css('option'))[2]; expect(select.nativeElement.value).toEqual('2: Object'); expect(secondNYC.nativeElement.selected).toBe(true); })); it('should work with null option', fakeAsync(() => { const fixture = initTest(NgModelSelectWithNullForm); const comp = fixture.componentInstance; comp.cities = [{'name': 'SF'}, {'name': 'NYC'}]; comp.selectedCity = null; fixture.detectChanges(); const select = fixture.debugElement.query(By.css('select')); select.nativeElement.value = '2: Object'; dispatchEvent(select.nativeElement, 'change'); fixture.detectChanges(); tick(); expect(comp.selectedCity!['name']).toEqual('NYC'); select.nativeElement.value = '0: null'; dispatchEvent(select.nativeElement, 'change'); fixture.detectChanges(); tick(); expect(comp.selectedCity).toEqual(null); })); it('should throw an error when compareWith is not a function', () => { const fixture = initTest(NgModelSelectWithCustomCompareFnForm); const comp = fixture.componentInstance; comp.compareFn = null!; expect(() => fixture.detectChanges()).toThrowError( /compareWith must be a function, but received null/, ); }); it('should compare options using provided compareWith function', fakeAsync(() => { if (isNode) return; const fixture = initTest(NgModelSelectWithCustomCompareFnForm); const comp = fixture.componentInstance; comp.selectedCity = {id: 1, name: 'SF'}; comp.cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'LA'}, ]; fixture.detectChanges(); tick(); const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual('0: Object'); expect(sfOption.nativeElement.selected).toBe(true); })); it('should support re-assigning the options array with compareWith', fakeAsync(() => { if (isNode) return; const fixture = initTest(NgModelSelectWithCustomCompareFnForm); fixture.componentInstance.selectedCity = {id: 1, name: 'SF'}; fixture.componentInstance.cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'NY'}, ]; fixture.detectChanges(); tick(); // Option IDs start out as 0 and 1, so setting the select value to "1: Object" // will select the second option (NY). const select = fixture.debugElement.query(By.css('select')); select.nativeElement.value = '1: Object'; dispatchEvent(select.nativeElement, 'change'); fixture.detectChanges(); const model = fixture.debugElement.children[0].injector.get(NgModel); expect(model.value).toEqual({id: 2, name: 'NY'}); fixture.componentInstance.cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'NY'}, ]; fixture.detectChanges(); tick(); // Now that the options array has been re-assigned, new option instances will // be created by ngFor. These instances will have different option IDs, subsequent // to the first: 2 and 3. For the second option to stay selected, the select // value will need to have the ID of the current second option: 3. const nyOption = fixture.debugElement.queryAll(By.css('option'))[1]; expect(select.nativeElement.value).toEqual('3: Object'); expect(nyOption.nativeElement.selected).toBe(true); })); }); });
{ "end_byte": 16461, "start_byte": 9868, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_16465_22230
describe('select multiple controls', () => { describe('in reactive forms', () => { it('should support primitive values', () => { if (isNode) return; const fixture = initTest(FormControlSelectMultiple); fixture.detectChanges(); const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual(`0: 'SF'`); expect(sfOption.nativeElement.selected).toBe(true); }); it('should support objects', () => { if (isNode) return; const fixture = initTest(FormControlSelectMultipleNgValue); fixture.detectChanges(); const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual('0: Object'); expect(sfOption.nativeElement.selected).toBe(true); }); it('should throw an error when compareWith is not a function', () => { const fixture = initTest(FormControlSelectMultipleWithCompareFn); fixture.componentInstance.compareFn = null!; expect(() => fixture.detectChanges()).toThrowError( /compareWith must be a function, but received null/, ); }); it('should compare options using provided compareWith function', fakeAsync(() => { if (isNode) return; const fixture = initTest(FormControlSelectMultipleWithCompareFn); fixture.detectChanges(); tick(); const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual('0: Object'); expect(sfOption.nativeElement.selected).toBe(true); })); }); describe('in template-driven forms', () => { let fixture: ComponentFixture<NgModelSelectMultipleForm>; let comp: NgModelSelectMultipleForm; beforeEach(() => { fixture = initTest(NgModelSelectMultipleForm); comp = fixture.componentInstance; comp.cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}]; }); const detectChangesAndTick = (): void => { fixture.detectChanges(); tick(); }; const setSelectedCities = (selectedCities: any): void => { comp.selectedCities = selectedCities; detectChangesAndTick(); }; const selectOptionViaUI = (valueString: string): void => { const select = fixture.debugElement.query(By.css('select')); select.nativeElement.value = valueString; dispatchEvent(select.nativeElement, 'change'); detectChangesAndTick(); }; const assertOptionElementSelectedState = (selectedStates: boolean[]): void => { const options = fixture.debugElement.queryAll(By.css('option')); if (options.length !== selectedStates.length) { throw 'the selected state values to assert does not match the number of options'; } for (let i = 0; i < selectedStates.length; i++) { expect(options[i].nativeElement.selected).toBe(selectedStates[i]); } }; it('verify that native `selectedOptions` field is used while detecting the list of selected options', fakeAsync(() => { if (isNode || !HTMLSelectElement.prototype.hasOwnProperty('selectedOptions')) return; const spy = spyOnProperty( HTMLSelectElement.prototype, 'selectedOptions', 'get', ).and.callThrough(); setSelectedCities([]); selectOptionViaUI('1: Object'); assertOptionElementSelectedState([false, true, false]); expect(spy).toHaveBeenCalled(); })); it('should reflect state of model after option selected and new options subsequently added', fakeAsync(() => { if (isNode) return; setSelectedCities([]); selectOptionViaUI('1: Object'); assertOptionElementSelectedState([false, true, false]); comp.cities.push({'name': 'Chicago'}); detectChangesAndTick(); assertOptionElementSelectedState([false, true, false, false]); })); it('should reflect state of model after option selected and then other options removed', fakeAsync(() => { if (isNode) return; setSelectedCities([]); selectOptionViaUI('1: Object'); assertOptionElementSelectedState([false, true, false]); comp.cities.pop(); detectChangesAndTick(); assertOptionElementSelectedState([false, true]); })); }); it('should throw an error when compareWith is not a function', () => { const fixture = initTest(NgModelSelectMultipleWithCustomCompareFnForm); const comp = fixture.componentInstance; comp.compareFn = null!; expect(() => fixture.detectChanges()).toThrowError( /compareWith must be a function, but received null/, ); }); it('should compare options using provided compareWith function', fakeAsync(() => { if (isNode) return; const fixture = initTest(NgModelSelectMultipleWithCustomCompareFnForm); const comp = fixture.componentInstance; comp.cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'LA'}, ]; comp.selectedCities = [comp.cities[0]]; fixture.detectChanges(); tick(); const select = fixture.debugElement.query(By.css('select')); const sfOption = fixture.debugElement.query(By.css('option')); expect(select.nativeElement.value).toEqual('0: Object'); expect(sfOption.nativeElement.selected).toBe(true); })); }); describe('should support <type=radio>', () => {
{ "end_byte": 22230, "start_byte": 16465, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_22235_32385
describe('in reactive forms', () => { it('should support basic functionality', () => { const fixture = initTest(FormControlRadioButtons); const form = new FormGroup({ 'food': new FormControl('fish'), 'drink': new FormControl('sprite'), }); fixture.componentInstance.form = form; fixture.detectChanges(); // model -> view const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); dispatchEvent(inputs[0].nativeElement, 'change'); fixture.detectChanges(); // view -> model expect(form.get('food')!.value).toEqual('chicken'); expect(inputs[1].nativeElement.checked).toEqual(false); form.get('food')!.setValue('fish'); fixture.detectChanges(); // programmatic change -> view expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); }); it('should support an initial undefined value', () => { const fixture = initTest(FormControlRadioButtons); const form = new FormGroup({'food': new FormControl(), 'drink': new FormControl()}); fixture.componentInstance.form = form; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(false); }); it('should reset properly', () => { const fixture = initTest(FormControlRadioButtons); const form = new FormGroup({ 'food': new FormControl('fish'), 'drink': new FormControl('sprite'), }); fixture.componentInstance.form = form; fixture.detectChanges(); form.reset(); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(false); }); it('should properly set value to null and undefined', () => { const fixture = initTest(FormControlRadioButtons); const form: FormGroup = new FormGroup({ 'food': new FormControl('chicken'), 'drink': new FormControl('sprite'), }); fixture.componentInstance.form = form; fixture.detectChanges(); form.get('food')!.setValue(null); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); form.get('food')!.setValue('chicken'); fixture.detectChanges(); form.get('food')!.setValue(undefined); fixture.detectChanges(); expect(inputs[0].nativeElement.checked).toEqual(false); }); it('should use formControlName to group radio buttons when name is absent', () => { const fixture = initTest(FormControlRadioButtons); const foodCtrl = new FormControl('fish'); const drinkCtrl = new FormControl('sprite'); fixture.componentInstance.form = new FormGroup({'food': foodCtrl, 'drink': drinkCtrl}); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); dispatchEvent(inputs[0].nativeElement, 'change'); inputs[0].nativeElement.checked = true; fixture.detectChanges(); const value = fixture.componentInstance.form.value; expect(value.food).toEqual('chicken'); expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); drinkCtrl.setValue('cola'); fixture.detectChanges(); expect(inputs[0].nativeElement.checked).toEqual(true); expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(true); expect(inputs[3].nativeElement.checked).toEqual(false); }); it('should support removing controls from <type=radio>', () => { const fixture = initTest(FormControlRadioButtons); const showRadio = new FormControl('yes'); const form: FormGroup = new FormGroup({ 'food': new FormControl('fish'), 'drink': new FormControl('sprite'), }); fixture.componentInstance.form = form; fixture.componentInstance.showRadio = showRadio; showRadio.valueChanges.subscribe((change) => { change === 'yes' ? form.addControl('food', new FormControl('fish')) : form.removeControl('food'); }); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('[value="no"]')); dispatchEvent(input.nativeElement, 'change'); fixture.detectChanges(); expect(form.value).toEqual({drink: 'sprite'}); }); it('should differentiate controls on different levels with the same name', () => { TestBed.overrideComponent(FormControlRadioButtons, { set: { template: ` <div [formGroup]="form"> <input type="radio" formControlName="food" value="chicken"> <input type="radio" formControlName="food" value="fish"> <div formGroupName="nested"> <input type="radio" formControlName="food" value="chicken"> <input type="radio" formControlName="food" value="fish"> </div> </div> `, }, }); const fixture = initTest(FormControlRadioButtons); const form = new FormGroup({ food: new FormControl('fish'), nested: new FormGroup({food: new FormControl('fish')}), }); fixture.componentInstance.form = form; fixture.detectChanges(); // model -> view const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); dispatchEvent(inputs[0].nativeElement, 'change'); fixture.detectChanges(); // view -> model expect(form.get('food')!.value).toEqual('chicken'); expect(form.get('nested.food')!.value).toEqual('fish'); expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); }); it('should disable all radio buttons when disable() is called', () => { const fixture = initTest(FormControlRadioButtons); const form = new FormGroup({food: new FormControl('fish'), drink: new FormControl('cola')}); fixture.componentInstance.form = form; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.disabled).toEqual(false); expect(inputs[1].nativeElement.disabled).toEqual(false); expect(inputs[2].nativeElement.disabled).toEqual(false); expect(inputs[3].nativeElement.disabled).toEqual(false); form.get('food')!.disable(); expect(inputs[0].nativeElement.disabled).toEqual(true); expect(inputs[1].nativeElement.disabled).toEqual(true); expect(inputs[2].nativeElement.disabled).toEqual(false); expect(inputs[3].nativeElement.disabled).toEqual(false); form.disable(); expect(inputs[0].nativeElement.disabled).toEqual(true); expect(inputs[1].nativeElement.disabled).toEqual(true); expect(inputs[2].nativeElement.disabled).toEqual(true); expect(inputs[3].nativeElement.disabled).toEqual(true); form.enable(); expect(inputs[0].nativeElement.disabled).toEqual(false); expect(inputs[1].nativeElement.disabled).toEqual(false); expect(inputs[2].nativeElement.disabled).toEqual(false); expect(inputs[3].nativeElement.disabled).toEqual(false); }); it('should disable all radio buttons when initially disabled', () => { const fixture = initTest(FormControlRadioButtons); const form = new FormGroup({ food: new FormControl({value: 'fish', disabled: true}), drink: new FormControl('cola'), }); fixture.componentInstance.form = form; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.disabled).toEqual(true); expect(inputs[1].nativeElement.disabled).toEqual(true); expect(inputs[2].nativeElement.disabled).toEqual(false); expect(inputs[3].nativeElement.disabled).toEqual(false); }); it('should work with reusing controls', () => { const fixture = initTest(FormControlRadioButtons); const food = new FormControl('chicken'); fixture.componentInstance.form = new FormGroup({ 'food': food, 'drink': new FormControl(''), }); fixture.detectChanges(); const newForm = new FormGroup({'food': food, 'drink': new FormControl('')}); fixture.componentInstance.form = newForm; fixture.detectChanges(); newForm.setValue({food: 'fish', drink: ''}); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toBe(false); expect(inputs[1].nativeElement.checked).toBe(true); }); });
{ "end_byte": 32385, "start_byte": 22235, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_32391_39913
describe('in template-driven forms', () => { it('should support basic functionality', fakeAsync(() => { const fixture = initTest(NgModelRadioForm); fixture.componentInstance.food = 'fish'; fixture.detectChanges(); tick(); // model -> view const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); dispatchEvent(inputs[0].nativeElement, 'change'); tick(); // view -> model expect(fixture.componentInstance.food).toEqual('chicken'); expect(inputs[1].nativeElement.checked).toEqual(false); })); it('should support multiple named <type=radio> groups', fakeAsync(() => { const fixture = initTest(NgModelRadioForm); fixture.componentInstance.food = 'fish'; fixture.componentInstance.drink = 'sprite'; fixture.detectChanges(); tick(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(true); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); dispatchEvent(inputs[0].nativeElement, 'change'); tick(); expect(fixture.componentInstance.food).toEqual('chicken'); expect(fixture.componentInstance.drink).toEqual('sprite'); expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(true); })); it('should support initial undefined value', fakeAsync(() => { const fixture = initTest(NgModelRadioForm); fixture.detectChanges(); tick(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[3].nativeElement.checked).toEqual(false); })); it('should support resetting properly', fakeAsync(() => { const fixture = initTest(NgModelRadioForm); fixture.componentInstance.food = 'chicken'; fixture.detectChanges(); tick(); const form = fixture.debugElement.query(By.css('form')); dispatchEvent(form.nativeElement, 'reset'); fixture.detectChanges(); tick(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(false); })); it('should support setting value to null and undefined', fakeAsync(() => { const fixture = initTest(NgModelRadioForm); fixture.componentInstance.food = 'chicken'; fixture.detectChanges(); tick(); fixture.componentInstance.food = null!; fixture.detectChanges(); tick(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(false); fixture.componentInstance.food = 'chicken'; fixture.detectChanges(); tick(); fixture.componentInstance.food = undefined!; fixture.detectChanges(); tick(); expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(false); })); it('should disable radio controls properly with programmatic call', fakeAsync(() => { const fixture = initTest(NgModelRadioForm); fixture.componentInstance.food = 'fish'; fixture.detectChanges(); tick(); const form = fixture.debugElement.children[0].injector.get(NgForm); form.control.get('food')!.disable(); tick(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.disabled).toBe(true); expect(inputs[1].nativeElement.disabled).toBe(true); expect(inputs[2].nativeElement.disabled).toBe(false); expect(inputs[3].nativeElement.disabled).toBe(false); form.control.disable(); tick(); expect(inputs[0].nativeElement.disabled).toBe(true); expect(inputs[1].nativeElement.disabled).toBe(true); expect(inputs[2].nativeElement.disabled).toBe(true); expect(inputs[3].nativeElement.disabled).toBe(true); form.control.enable(); tick(); expect(inputs[0].nativeElement.disabled).toBe(false); expect(inputs[1].nativeElement.disabled).toBe(false); expect(inputs[2].nativeElement.disabled).toBe(false); expect(inputs[3].nativeElement.disabled).toBe(false); })); }); }); describe('should support <type=range>', () => { describe('in reactive forms', () => { it('with basic use case', () => { const fixture = initTest(FormControlRangeInput); const control = new FormControl(10); fixture.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('10'); input.nativeElement.value = '20'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(control.value).toEqual(20); }); it('when value is cleared in the UI', () => { const fixture = initTest(FormControlNumberInput); const control = new FormControl(10, Validators.required); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = ''; dispatchEvent(input.nativeElement, 'input'); expect(control.valid).toBe(false); expect(control.value).toEqual(null); input.nativeElement.value = '0'; dispatchEvent(input.nativeElement, 'input'); expect(control.valid).toBe(true); expect(control.value).toEqual(0); }); it('when value is cleared programmatically', () => { const fixture = initTest(FormControlNumberInput); const control = new FormControl(10); fixture.componentInstance.control = control; fixture.detectChanges(); control.setValue(null); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual(''); }); }); describe('in template-driven forms', () => { it('with basic use case', fakeAsync(() => { const fixture = initTest(NgModelRangeForm); // model -> view fixture.componentInstance.val = 4; fixture.detectChanges(); tick(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toBe('4'); fixture.detectChanges(); tick(); const newVal = '4'; input.triggerEventHandler('input', {target: {value: newVal}}); tick(); // view -> model fixture.detectChanges(); expect(typeof fixture.componentInstance.val).toBe('number'); })); }); });
{ "end_byte": 39913, "start_byte": 32391, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_39917_49667
describe('custom value accessors', () => { describe('in reactive forms', () => { it('should support basic functionality', () => { const fixture = initTest(WrappedValueForm, WrappedValue); const form = new FormGroup({'login': new FormControl('aa')}); fixture.componentInstance.form = form; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('!aa!'); input.nativeElement.value = '!bb!'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(form.value).toEqual({'login': 'bb'}); // custom validator expect(form.get('login')!.errors).toEqual({'err': true}); form.setValue({login: 'expected'}); expect(form.get('login')!.errors).toEqual(null); }); it("should support non builtin input elements that fire a change event without a 'target' property", () => { const fixture = initTest(MyInputForm, MyInput); fixture.componentInstance.form = new FormGroup({'login': new FormControl('aa')}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('my-input')); expect(input.componentInstance.value).toEqual('!aa!'); input.componentInstance.value = '!bb!'; input.componentInstance.onInput.subscribe((value: any) => { expect(fixture.componentInstance.form.value).toEqual({'login': 'bb'}); }); input.componentInstance.dispatchChangeEvent(); }); it('should support custom accessors without setDisabledState - formControlName', () => { const fixture = initTest(WrappedValueForm, WrappedValue); fixture.componentInstance.form = new FormGroup({ 'login': new FormControl({value: 'aa', disabled: true}), }); fixture.detectChanges(); expect(fixture.componentInstance.form.status).toEqual('DISABLED'); expect(fixture.componentInstance.form.get('login')!.status).toEqual('DISABLED'); }); it('should support custom accessors without setDisabledState - formControlDirective', () => { TestBed.overrideComponent(FormControlComp, { set: {template: `<input type="text" [formControl]="control" wrapped-value>`}, }); const fixture = initTest(FormControlComp); fixture.componentInstance.control = new FormControl({value: 'aa', disabled: true}); fixture.detectChanges(); expect(fixture.componentInstance.control.status).toEqual('DISABLED'); }); describe('should support custom accessors with setDisabledState - formControlName', () => { let fixture: ComponentFixture<CvaWithDisabledStateForm>; beforeEach(() => { fixture = initTest(CvaWithDisabledStateForm, CvaWithDisabledState); }); it('sets the disabled state when the control is initially disabled', () => { fixture.componentInstance.form = new FormGroup({ 'login': new FormControl({value: 'aa', disabled: true}), }); fixture.detectChanges(); expect(fixture.componentInstance.form.status).toEqual('DISABLED'); expect(fixture.componentInstance.form.get('login')!.status).toEqual('DISABLED'); expect( fixture.debugElement.query(By.directive(CvaWithDisabledState)).nativeElement .textContent, ).toContain('DISABLED'); }); it('sets the enabled state when the control is initially enabled', () => { fixture.componentInstance.form = new FormGroup({ 'login': new FormControl({value: 'aa', disabled: false}), }); fixture.detectChanges(); expect(fixture.componentInstance.form.status).toEqual('VALID'); expect(fixture.componentInstance.form.get('login')!.status).toEqual('VALID'); expect( fixture.debugElement.query(By.directive(CvaWithDisabledState)).nativeElement .textContent, ).toContain('ENABLED'); }); }); it('should populate control in ngOnInit when injecting NgControl', () => { const fixture = initTest(MyInputForm, MyInput); fixture.componentInstance.form = new FormGroup({'login': new FormControl('aa')}); fixture.detectChanges(); expect(fixture.componentInstance.myInput!.control).toBeDefined(); expect(fixture.componentInstance.myInput!.control).toEqual( fixture.componentInstance.myInput!.controlDir.control, ); }); }); describe('in template-driven forms', () => { it('should support standard writing to view and model', waitForAsync(() => { const fixture = initTest(NgModelCustomWrapper, NgModelCustomComp); fixture.componentInstance.name = 'Nancy'; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); fixture.whenStable().then(() => { // model -> view const customInput = fixture.debugElement.query(By.css('[name="custom"]')); expect(customInput.nativeElement.value).toEqual('Nancy'); customInput.nativeElement.value = 'Carson'; dispatchEvent(customInput.nativeElement, 'input'); fixture.detectChanges(); // view -> model expect(fixture.componentInstance.name).toEqual('Carson'); }); }); })); }); describe('`ngModel` value accessor inside an OnPush component', () => { it('should run change detection and update the value', fakeAsync(async () => { @Component({ selector: 'parent', template: '<child [ngModel]="value"></child>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class Parent { value!: string; constructor(private ref: ChangeDetectorRef) {} setTimeoutAndChangeValue(): void { setTimeout(() => { this.value = 'Carson'; this.ref.detectChanges(); }, 50); } } @Component({ selector: 'child', template: 'Value: {{ value }}', providers: [{provide: NG_VALUE_ACCESSOR, useExisting: Child, multi: true}], standalone: false, }) class Child implements ControlValueAccessor { value!: string; writeValue(value: string): void { this.value = value; } registerOnChange(): void {} registerOnTouched(): void {} } const fixture = initTest(Parent, Child); fixture.componentInstance.value = 'Nancy'; fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); await fixture.whenStable(); const child = fixture.debugElement.query(By.css('child')); // Let's ensure that the initial value has been set, because previously // it wasn't set inside an `OnPush` component. expect(child.nativeElement.innerHTML).toEqual('Value: Nancy'); fixture.componentInstance.setTimeoutAndChangeValue(); tick(50); fixture.detectChanges(); await fixture.whenStable(); expect(child.nativeElement.innerHTML).toEqual('Value: Carson'); })); }); }); }); describe('value accessors in reactive forms with custom options', () => { function initTest<T>(component: Type<T>, ...directives: Type<any>[]): ComponentFixture<T> { TestBed.configureTestingModule({ declarations: [component, ...directives], imports: [ ReactiveFormsModule.withConfig({callSetDisabledState: 'whenDisabledForLegacyCode'}), ], }); return TestBed.createComponent(component); } describe('should support custom accessors with setDisabledState', () => { let fixture: ComponentFixture<CvaWithDisabledStateForm>; beforeEach(() => { fixture = initTest(CvaWithDisabledStateForm, CvaWithDisabledState); }); it('does not set the enabled state when the control is initially enabled', () => { fixture.componentInstance.form = new FormGroup({ 'login': new FormControl({value: 'aa', disabled: false}), }); fixture.detectChanges(); expect(fixture.componentInstance.form.status).toEqual('VALID'); expect(fixture.componentInstance.form.get('login')!.status).toEqual('VALID'); expect( fixture.debugElement.query(By.directive(CvaWithDisabledState)).nativeElement.textContent, ).toContain('UNSET'); }); }); }); @Component({ selector: 'form-control-comp', template: `<input type="text" [formControl]="control">`, standalone: false, }) export class FormControlComp { control!: FormControl; } @Component({ selector: 'form-group-comp', template: ` <form [formGroup]="form" (ngSubmit)="event=$event"> <input type="text" formControlName="login"> </form>`, standalone: false, }) export class FormGroupComp { control!: FormControl; form!: FormGroup; myGroup!: FormGroup; event!: Event; } @Component({ selector: 'form-control-number-input', template: `<input type="number" [formControl]="control">`, standalone: false, }) class FormControlNumberInput { control!: FormControl; } @Component({ selector: 'form-control-name-select', template: ` <div [formGroup]="form"> <select formControlName="city"> <option *ngFor="let c of cities" [value]="c"></option> </select> </div>`, standalone: false, }) class FormControlNameSelect { cities = ['SF', 'NY']; form = new FormGroup({city: new FormControl('SF')}); }
{ "end_byte": 49667, "start_byte": 39917, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_49669_56381
@Component({ selector: 'form-control-select-ngValue', template: ` <div [formGroup]="form"> <select formControlName="city"> <option *ngFor="let c of cities" [ngValue]="c">{{c.name}}</option> </select> </div>`, standalone: false, }) class FormControlSelectNgValue { cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'NY'}, ]; form = new FormGroup({city: new FormControl(this.cities[0])}); } @Component({ selector: 'form-control-select-compare-with', template: ` <div [formGroup]="form"> <select formControlName="city" [compareWith]="compareFn"> <option *ngFor="let c of cities" [ngValue]="c">{{c.name}}</option> </select> </div>`, standalone: false, }) class FormControlSelectWithCompareFn { compareFn: (o1: any, o2: any) => boolean = (o1: any, o2: any) => o1 && o2 ? o1.id === o2.id : o1 === o2; cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'NY'}, ]; form = new FormGroup({city: new FormControl({id: 1, name: 'SF'})}); } @Component({ selector: 'form-control-select-multiple', template: ` <div [formGroup]="form"> <select multiple formControlName="city"> <option *ngFor="let c of cities" [value]="c">{{c}}</option> </select> </div>`, standalone: false, }) class FormControlSelectMultiple { cities = ['SF', 'NY']; form = new FormGroup({city: new FormControl(['SF'])}); } @Component({ selector: 'form-control-select-multiple', template: ` <div [formGroup]="form"> <select multiple formControlName="city"> <option *ngFor="let c of cities" [ngValue]="c">{{c.name}}</option> </select> </div>`, standalone: false, }) class FormControlSelectMultipleNgValue { cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'NY'}, ]; form = new FormGroup({city: new FormControl([this.cities[0]])}); } @Component({ selector: 'form-control-select-multiple-compare-with', template: ` <div [formGroup]="form"> <select multiple formControlName="city" [compareWith]="compareFn"> <option *ngFor="let c of cities" [ngValue]="c">{{c.name}}</option> </select> </div>`, standalone: false, }) class FormControlSelectMultipleWithCompareFn { compareFn: (o1: any, o2: any) => boolean = (o1: any, o2: any) => o1 && o2 ? o1.id === o2.id : o1 === o2; cities = [ {id: 1, name: 'SF'}, {id: 2, name: 'NY'}, ]; form = new FormGroup({city: new FormControl([{id: 1, name: 'SF'}])}); } @Component({ selector: 'ng-model-select-form', template: ` <select [(ngModel)]="selectedCity"> <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option> </select> `, standalone: false, }) class NgModelSelectForm { selectedCity: {[k: string]: string} = {}; cities: any[] = []; } @Component({ selector: 'ng-model-select-null-form', template: ` <select [(ngModel)]="selectedCity"> <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option> <option [ngValue]="null">Unspecified</option> </select> `, standalone: false, }) class NgModelSelectWithNullForm { selectedCity: {[k: string]: string} | null = {}; cities: any[] = []; } @Component({ selector: 'ng-model-select-compare-with', template: ` <select [(ngModel)]="selectedCity" [compareWith]="compareFn"> <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option> </select> `, standalone: false, }) class NgModelSelectWithCustomCompareFnForm { compareFn: (o1: any, o2: any) => boolean = (o1: any, o2: any) => o1 && o2 ? o1.id === o2.id : o1 === o2; selectedCity: any = {}; cities: any[] = []; } @Component({ selector: 'ng-model-select-multiple-compare-with', template: ` <select multiple [(ngModel)]="selectedCities" [compareWith]="compareFn"> <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option> </select> `, standalone: false, }) class NgModelSelectMultipleWithCustomCompareFnForm { compareFn: (o1: any, o2: any) => boolean = (o1: any, o2: any) => o1 && o2 ? o1.id === o2.id : o1 === o2; selectedCities: any[] = []; cities: any[] = []; } @Component({ selector: 'ng-model-select-multiple-form', template: ` <select multiple [(ngModel)]="selectedCities"> <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option> </select> `, standalone: false, }) class NgModelSelectMultipleForm { selectedCities!: any[]; cities: any[] = []; } @Component({ selector: 'form-control-range-input', template: `<input type="range" [formControl]="control">`, standalone: false, }) class FormControlRangeInput { control!: FormControl; } @Component({ selector: 'ng-model-range-form', template: '<input type="range" [(ngModel)]="val">', standalone: false, }) class NgModelRangeForm { val: any; } @Component({ selector: 'form-control-radio-buttons', template: ` <form [formGroup]="form" *ngIf="showRadio.value === 'yes'"> <input type="radio" formControlName="food" value="chicken"> <input type="radio" formControlName="food" value="fish"> <input type="radio" formControlName="drink" value="cola"> <input type="radio" formControlName="drink" value="sprite"> </form> <input type="radio" [formControl]="showRadio" value="yes"> <input type="radio" [formControl]="showRadio" value="no">`, standalone: false, }) export class FormControlRadioButtons { form!: FormGroup; showRadio = new FormControl('yes'); } @Component({ selector: 'ng-model-radio-form', template: ` <form> <input type="radio" name="food" [(ngModel)]="food" value="chicken"> <input type="radio" name="food" [(ngModel)]="food" value="fish"> <input type="radio" name="drink" [(ngModel)]="drink" value="cola"> <input type="radio" name="drink" [(ngModel)]="drink" value="sprite"> </form> `, standalone: false, }) class NgModelRadioForm { food!: string; drink!: string; } @Directive({ selector: '[wrapped-value]', host: {'(input)': 'handleOnInput($event.target.value)', '[value]': 'value'}, providers: [ {provide: NG_VALUE_ACCESSOR, multi: true, useExisting: WrappedValue}, {provide: NG_VALIDATORS, multi: true, useExisting: WrappedValue}, ], standalone: false, }) class WrappedValue implements ControlValueAccessor { value: any; onChange!: Function; writeValue(value: any) { this.value = `!${value}!`; } registerOnChange(fn: (value: any) => void) { this.onChange = fn; } registerOnTouched(fn: any) {} handleOnInput(value: any) { this.onChange(value.substring(1, value.length - 1)); } validate(c: AbstractControl) { return c.value === 'expected' ? null : {'err': true}; } }
{ "end_byte": 56381, "start_byte": 49669, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/value_accessor_integration_spec.ts_56383_59480
@Component({ selector: 'cva-with-disabled-state', template: ` <div *ngIf="disabled !== undefined">CALLED WITH {{disabled ? 'DISABLED' : 'ENABLED'}}</div> <div *ngIf="disabled === undefined">UNSET</div> `, providers: [{provide: NG_VALUE_ACCESSOR, multi: true, useExisting: CvaWithDisabledState}], standalone: false, }) class CvaWithDisabledState implements ControlValueAccessor { disabled?: boolean; onChange!: Function; writeValue(value: any) {} registerOnChange(fn: (value: any) => void) {} registerOnTouched(fn: any) {} setDisabledState(disabled: boolean) { this.disabled = disabled; } } @Component({ selector: 'wrapped-value-form', template: ` <div [formGroup]="form"> <cva-with-disabled-state formControlName="login"></cva-with-disabled-state> </div>`, standalone: false, }) class CvaWithDisabledStateForm { form!: FormGroup; } @Component({ selector: 'my-input', template: '', standalone: false, }) export class MyInput implements ControlValueAccessor { @Output('input') onInput = new EventEmitter(); value!: string; control: AbstractControl | null = null; constructor(public controlDir: NgControl) { controlDir.valueAccessor = this; } ngOnInit() { this.control = this.controlDir.control; } writeValue(value: any) { this.value = `!${value}!`; } registerOnChange(fn: (value: any) => void) { this.onInput.subscribe({next: fn}); } registerOnTouched(fn: any) {} dispatchChangeEvent() { this.onInput.emit(this.value.substring(1, this.value.length - 1)); } } @Component({ selector: 'my-input-form', template: ` <div [formGroup]="form"> <my-input formControlName="login"></my-input> </div>`, standalone: false, }) export class MyInputForm { form!: FormGroup; @ViewChild(MyInput) myInput: MyInput | null = null; } @Component({ selector: 'wrapped-value-form', template: ` <div [formGroup]="form"> <input type="text" formControlName="login" wrapped-value> </div>`, standalone: false, }) class WrappedValueForm { form!: FormGroup; } @Component({ selector: 'ng-model-custom-comp', template: ` <input name="custom" [(ngModel)]="model" (ngModelChange)="changeFn($event)" [disabled]="isDisabled"> `, providers: [{provide: NG_VALUE_ACCESSOR, multi: true, useExisting: NgModelCustomComp}], standalone: false, }) export class NgModelCustomComp implements ControlValueAccessor { model!: string; @Input('disabled') isDisabled: boolean = false; changeFn!: (value: any) => void; writeValue(value: any) { this.model = value; } registerOnChange(fn: (value: any) => void) { this.changeFn = fn; } registerOnTouched() {} setDisabledState(isDisabled: boolean) { this.isDisabled = isDisabled; } } @Component({ selector: 'ng-model-custom-wrapper', template: ` <form> <ng-model-custom-comp name="name" [(ngModel)]="name" [disabled]="isDisabled"></ng-model-custom-comp> </form> `, standalone: false, }) export class NgModelCustomWrapper { name!: string; isDisabled = false; }
{ "end_byte": 59480, "start_byte": 56383, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/value_accessor_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_0_3774
/** * @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 {ɵgetDOM as getDOM} from '@angular/common'; import { Component, Directive, ElementRef, forwardRef, Input, OnDestroy, Type, ViewChild, } from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import { AbstractControl, AsyncValidator, AsyncValidatorFn, COMPOSITION_BUFFER_MODE, ControlValueAccessor, FormArray, FormBuilder, FormControl, FormControlDirective, FormControlName, FormGroup, FormGroupDirective, FormsModule, MaxValidator, MinValidator, NG_ASYNC_VALIDATORS, NG_VALIDATORS, NG_VALUE_ACCESSOR, ReactiveFormsModule, Validator, Validators, } from '@angular/forms'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {dispatchEvent, sortedClassList} from '@angular/platform-browser/testing/src/browser_util'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {merge, NEVER, Observable, of, Subject, Subscription, timer} from 'rxjs'; import {map, tap} from 'rxjs/operators'; import { ControlEvent, FormControlStatus, FormResetEvent, FormSubmittedEvent, PristineChangeEvent, StatusChangeEvent, TouchedChangeEvent, ValueChangeEvent, } from '../src/model/abstract_model'; import {MyInput, MyInputForm} from './value_accessor_integration_spec'; // Produces a new @Directive (with a given selector) that represents a validator class. function createValidatorClass(selector: string) { @Directive({ selector, providers: [ { provide: NG_VALIDATORS, useClass: forwardRef(() => CustomValidator), multi: true, }, ], standalone: false, }) class CustomValidator implements Validator { validate(control: AbstractControl) { return null; } } return CustomValidator; } // Produces a new @Directive (with a given selector) that represents an async validator class. function createAsyncValidatorClass(selector: string) { @Directive({ selector, providers: [ { provide: NG_ASYNC_VALIDATORS, useClass: forwardRef(() => CustomValidator), multi: true, }, ], standalone: false, }) class CustomValidator implements AsyncValidator { validate(control: AbstractControl) { return Promise.resolve(null); } } return CustomValidator; } // Produces a new @Directive (with a given selector) that represents a value accessor. function createControlValueAccessor(selector: string) { @Directive({ selector, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CustomValueAccessor), multi: true, }, ], standalone: false, }) class CustomValueAccessor implements ControlValueAccessor { writeValue(value: any) {} registerOnChange(fn: (value: any) => void) {} registerOnTouched(fn: any) {} } return CustomValueAccessor; } // Pre-create classes for validators. const ViewValidatorA = createValidatorClass('[validators-a]'); const ViewValidatorB = createValidatorClass('[validators-b]'); const ViewValidatorC = createValidatorClass('[validators-c]'); // Pre-create classes for async validators. const AsyncViewValidatorA = createAsyncValidatorClass('[validators-a]'); const AsyncViewValidatorB = createAsyncValidatorClass('[validators-b]'); const AsyncViewValidatorC = createAsyncValidatorClass('[validators-c]'); // Pre-create classes for value accessors. const ValueAccessorA = createControlValueAccessor('[cva-a]'); const ValueAccessorB = createControlValueAccessor('[cva-b]');
{ "end_byte": 3774, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_3776_13580
escribe('reactive forms integration tests', () => { function initTest<T>(component: Type<T>, ...directives: Type<any>[]): ComponentFixture<T> { TestBed.configureTestingModule({ declarations: [component, ...directives], imports: [FormsModule, ReactiveFormsModule], }); return TestBed.createComponent(component); } function initReactiveFormsTest<T>( component: Type<T>, ...directives: Type<any>[] ): ComponentFixture<T> { TestBed.configureTestingModule({ declarations: [component, ...directives], imports: [ReactiveFormsModule], }); return TestBed.createComponent(component); } // Helper method that attaches a spy to a `validate` function on a Validator class. function validatorSpyOn(validatorClass: any) { return spyOn(validatorClass.prototype, 'validate').and.callThrough(); } describe('basic functionality', () => { it('should work with single controls', () => { const fixture = initTest(FormControlComp); const control = new FormControl('old value'); fixture.componentInstance.control = control; fixture.detectChanges(); // model -> view const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('old value'); input.nativeElement.value = 'updated value'; dispatchEvent(input.nativeElement, 'input'); // view -> model expect(control.value).toEqual('updated value'); }); it('should work with formGroups (model -> view)', () => { const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({'login': new FormControl('loginValue')}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('loginValue'); }); it('should add novalidate by default to form', () => { const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({'login': new FormControl('loginValue')}); fixture.detectChanges(); const form = fixture.debugElement.query(By.css('form')); expect(form.nativeElement.getAttribute('novalidate')).toEqual(''); }); it('work with formGroups (view -> model)', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('oldValue')}); fixture.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'updatedValue'; dispatchEvent(input.nativeElement, 'input'); expect(form.value).toEqual({'login': 'updatedValue'}); }); }); describe('re-bound form groups', () => { it('should update DOM elements initially', () => { const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({'login': new FormControl('oldValue')}); fixture.detectChanges(); fixture.componentInstance.form = new FormGroup({'login': new FormControl('newValue')}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('newValue'); }); it('should update model when UI changes', () => { const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({'login': new FormControl('oldValue')}); fixture.detectChanges(); const newForm = new FormGroup({'login': new FormControl('newValue')}); fixture.componentInstance.form = newForm; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'Nancy'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); expect(newForm.value).toEqual({login: 'Nancy'}); newForm.setValue({login: 'Carson'}); fixture.detectChanges(); expect(input.nativeElement.value).toEqual('Carson'); }); it('should update nested form group model when UI changes', () => { const fixture = initTest(NestedFormGroupNameComp); fixture.componentInstance.form = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(), 'password': new FormControl()}), }); fixture.detectChanges(); const newForm = new FormGroup({ 'signin': new FormGroup({ 'login': new FormControl('Nancy'), 'password': new FormControl('secret'), }), }); fixture.componentInstance.form = newForm; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.value).toEqual('Nancy'); expect(inputs[1].nativeElement.value).toEqual('secret'); inputs[0].nativeElement.value = 'Carson'; dispatchEvent(inputs[0].nativeElement, 'input'); fixture.detectChanges(); expect(newForm.value).toEqual({signin: {login: 'Carson', password: 'secret'}}); newForm.setValue({signin: {login: 'Bess', password: 'otherpass'}}); fixture.detectChanges(); expect(inputs[0].nativeElement.value).toEqual('Bess'); }); it('should pick up dir validators from form controls', () => { const fixture = initTest(LoginIsEmptyWrapper, LoginIsEmptyValidator); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = form; fixture.detectChanges(); expect(form.get('login')!.errors).toEqual({required: true}); const newForm = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = newForm; fixture.detectChanges(); expect(newForm.get('login')!.errors).toEqual({required: true}); }); it('should pick up dir validators from nested form groups', () => { const fixture = initTest(NestedFormGroupNameComp, LoginIsEmptyValidator); const form = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(''), 'password': new FormControl('')}), }); fixture.componentInstance.form = form; fixture.detectChanges(); expect(form.get('signin')!.valid).toBe(false); const newForm = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(''), 'password': new FormControl('')}), }); fixture.componentInstance.form = newForm; fixture.detectChanges(); expect(form.get('signin')!.valid).toBe(false); }); it('should strip named controls that are not found', () => { const fixture = initTest(NestedFormGroupNameComp, LoginIsEmptyValidator); const form: FormGroup = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(''), 'password': new FormControl('')}), }); fixture.componentInstance.form = form; fixture.detectChanges(); form.addControl('email', new FormControl('email')); fixture.detectChanges(); let emailInput = fixture.debugElement.query(By.css('[formControlName="email"]')); expect(emailInput.nativeElement.value).toEqual('email'); const newForm = new FormGroup({ 'signin': new FormGroup({'login': new FormControl(''), 'password': new FormControl('')}), }); fixture.componentInstance.form = newForm; fixture.detectChanges(); emailInput = fixture.debugElement.query(By.css('[formControlName="email"]')); expect(emailInput as any).toBe(null); // TODO: remove `any` after #22449 is closed. }); it('should strip array controls that are not found', () => { const fixture = initTest(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); let inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[2]).not.toBeDefined(); cityArray.push(new FormControl('LA')); fixture.detectChanges(); inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[2]).toBeDefined(); const newArr = new FormArray([new FormControl('SF'), new FormControl('NY')]); const newForm = new FormGroup({cities: newArr}); fixture.componentInstance.form = newForm; fixture.componentInstance.cityArray = newArr; fixture.detectChanges(); inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[2]).not.toBeDefined(); }); it('should sync the disabled state if it changes right after a group is re-bound', () => { @Component({ template: ` <form [formGroup]="form"> <input formControlName="input"> </form> `, standalone: false, }) class App { form: FormGroup; constructor(private _fb: FormBuilder) { this.form = this._getForm(); } private _getForm() { return this._fb.group({'input': 'value'}); } recreateAndDisable() { this.form = this._getForm(); this.form.disable(); } } const fixture = initTest(App); fixture.detectChanges(); const input = fixture.nativeElement.querySelector('input'); expect(input.disabled).toBe(false); fixture.componentInstance.recreateAndDisable(); fixture.detectChanges(); expect(input.disabled).toBe(true); });
{ "end_byte": 13580, "start_byte": 3776, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_13586_21098
escribe('nested control rebinding', () => { it('should attach dir to control when leaf control changes', () => { const form: FormGroup = new FormGroup({'login': new FormControl('oldValue')}); const fixture = initTest(FormGroupComp); fixture.componentInstance.form = form; fixture.detectChanges(); form.removeControl('login'); form.addControl('login', new FormControl('newValue')); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('newValue'); input.nativeElement.value = 'user input'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); expect(form.value).toEqual({login: 'user input'}); form.setValue({login: 'Carson'}); fixture.detectChanges(); expect(input.nativeElement.value).toEqual('Carson'); }); it('should attach dirs to all child controls when group control changes', () => { const fixture = initTest(NestedFormGroupNameComp, LoginIsEmptyValidator); const form: FormGroup = new FormGroup({ signin: new FormGroup({ login: new FormControl('oldLogin'), password: new FormControl('oldPassword'), }), }); fixture.componentInstance.form = form; fixture.detectChanges(); form.removeControl('signin'); form.addControl( 'signin', new FormGroup({ login: new FormControl('newLogin'), password: new FormControl('newPassword'), }), ); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.value).toEqual('newLogin'); expect(inputs[1].nativeElement.value).toEqual('newPassword'); inputs[0].nativeElement.value = 'user input'; dispatchEvent(inputs[0].nativeElement, 'input'); fixture.detectChanges(); expect(form.value).toEqual({signin: {login: 'user input', password: 'newPassword'}}); form.setValue({signin: {login: 'Carson', password: 'Drew'}}); fixture.detectChanges(); expect(inputs[0].nativeElement.value).toEqual('Carson'); expect(inputs[1].nativeElement.value).toEqual('Drew'); }); it('should attach dirs to all present child controls when array control changes', () => { const fixture = initTest(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form: FormGroup = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); form.removeControl('cities'); form.addControl('cities', new FormArray([new FormControl('LA')])); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('LA'); input.nativeElement.value = 'MTV'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); expect(form.value).toEqual({cities: ['MTV']}); form.setValue({cities: ['LA']}); fixture.detectChanges(); expect(input.nativeElement.value).toEqual('LA'); }); it('should remove controls correctly after re-binding a form array', () => { const fixture = initTest(FormArrayComp); const cityArray = new FormArray([ new FormControl('SF'), new FormControl('NY'), new FormControl('LA'), ]); const form = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const newArr = new FormArray([ new FormControl('SF'), new FormControl('NY'), new FormControl('LA'), ]); fixture.componentInstance.cityArray = newArr; form.setControl('cities', newArr); fixture.detectChanges(); newArr.removeAt(0); fixture.detectChanges(); let inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.value).toEqual('NY'); expect(inputs[1].nativeElement.value).toEqual('LA'); let firstInput = inputs[0].nativeElement; firstInput.value = 'new value'; dispatchEvent(firstInput, 'input'); fixture.detectChanges(); expect(newArr.value).toEqual(['new value', 'LA']); newArr.removeAt(0); fixture.detectChanges(); firstInput = fixture.debugElement.query(By.css('input')).nativeElement; firstInput.value = 'last one'; dispatchEvent(firstInput, 'input'); fixture.detectChanges(); expect(newArr.value).toEqual(['last one']); newArr.get([0])!.setValue('set value'); fixture.detectChanges(); firstInput = fixture.debugElement.query(By.css('input')).nativeElement; expect(firstInput.value).toEqual('set value'); }); it('should submit properly after removing controls on a re-bound array', () => { const fixture = initTest(FormArrayComp); const cityArray = new FormArray([ new FormControl('SF'), new FormControl('NY'), new FormControl('LA'), ]); const form = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const newArr = new FormArray([ new FormControl('SF'), new FormControl('NY'), new FormControl('LA'), ]); fixture.componentInstance.cityArray = newArr; form.setControl('cities', newArr); fixture.detectChanges(); newArr.removeAt(0); fixture.detectChanges(); const formEl = fixture.debugElement.query(By.css('form')); expect(() => dispatchEvent(formEl.nativeElement, 'submit')).not.toThrowError(); }); it('should insert controls properly on a re-bound array', () => { const fixture = initTest(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const newArr = new FormArray([new FormControl('SF'), new FormControl('NY')]); fixture.componentInstance.cityArray = newArr; form.setControl('cities', newArr); fixture.detectChanges(); newArr.insert(1, new FormControl('LA')); fixture.detectChanges(); let inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.value).toEqual('SF'); expect(inputs[1].nativeElement.value).toEqual('LA'); expect(inputs[2].nativeElement.value).toEqual('NY'); const lastInput = inputs[2].nativeElement; lastInput.value = 'Tulsa'; dispatchEvent(lastInput, 'input'); fixture.detectChanges(); expect(newArr.value).toEqual(['SF', 'LA', 'Tulsa']); newArr.get([2])!.setValue('NY'); fixture.detectChanges(); expect(lastInput.value).toEqual('NY'); }); }); });
{ "end_byte": 21098, "start_byte": 13586, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_21102_23932
escribe('form arrays', () => { it('should support form arrays', () => { const fixture = initTest(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); // model -> view expect(inputs[0].nativeElement.value).toEqual('SF'); expect(inputs[1].nativeElement.value).toEqual('NY'); expect(form.value).toEqual({cities: ['SF', 'NY']}); inputs[0].nativeElement.value = 'LA'; dispatchEvent(inputs[0].nativeElement, 'input'); fixture.detectChanges(); // view -> model expect(form.value).toEqual({cities: ['LA', 'NY']}); }); it('should support pushing new controls to form arrays', () => { const fixture = initTest(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); cityArray.push(new FormControl('LA')); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[2].nativeElement.value).toEqual('LA'); expect(form.value).toEqual({cities: ['SF', 'NY', 'LA']}); }); it('should support form groups nested in form arrays', () => { const fixture = initTest(FormArrayNestedGroup); const cityArray = new FormArray([ new FormGroup({town: new FormControl('SF'), state: new FormControl('CA')}), new FormGroup({town: new FormControl('NY'), state: new FormControl('NY')}), ]); const form = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.value).toEqual('SF'); expect(inputs[1].nativeElement.value).toEqual('CA'); expect(inputs[2].nativeElement.value).toEqual('NY'); expect(inputs[3].nativeElement.value).toEqual('NY'); expect(form.value).toEqual({ cities: [ {town: 'SF', state: 'CA'}, {town: 'NY', state: 'NY'}, ], }); inputs[0].nativeElement.value = 'LA'; dispatchEvent(inputs[0].nativeElement, 'input'); fixture.detectChanges(); expect(form.value).toEqual({ cities: [ {town: 'LA', state: 'CA'}, {town: 'NY', state: 'NY'}, ], }); }); });
{ "end_byte": 23932, "start_byte": 21102, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_23936_34569
escribe('programmatic changes', () => { it('should update the value in the DOM when setValue() is called', () => { const fixture = initTest(FormGroupComp); const login = new FormControl('oldValue'); const form = new FormGroup({'login': login}); fixture.componentInstance.form = form; fixture.detectChanges(); login.setValue('newValue'); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.value).toEqual('newValue'); }); describe('disabled controls', () => { it('should add disabled attribute to an individual control when instantiated as disabled', () => { const fixture = initTest(FormControlComp); const control = new FormControl({value: 'some value', disabled: true}); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.disabled).toBe(true); control.enable(); fixture.detectChanges(); expect(input.nativeElement.disabled).toBe(false); }); it('should add disabled attribute to formControlName when instantiated as disabled', () => { const fixture = initTest(FormGroupComp); const control = new FormControl({value: 'some value', disabled: true}); fixture.componentInstance.form = new FormGroup({login: control}); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.disabled).toBe(true); control.enable(); fixture.detectChanges(); expect(input.nativeElement.disabled).toBe(false); }); it('should add disabled attribute to an individual control when disable() is called', () => { const fixture = initTest(FormControlComp); const control = new FormControl('some value'); fixture.componentInstance.control = control; fixture.detectChanges(); control.disable(); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')); expect(input.nativeElement.disabled).toBe(true); control.enable(); fixture.detectChanges(); expect(input.nativeElement.disabled).toBe(false); }); it('should add disabled attribute to child controls when disable() is called on group', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('login')}); fixture.componentInstance.form = form; fixture.detectChanges(); form.disable(); fixture.detectChanges(); const inputs = fixture.debugElement.queryAll(By.css('input')); expect(inputs[0].nativeElement.disabled).toBe(true); form.enable(); fixture.detectChanges(); expect(inputs[0].nativeElement.disabled).toBe(false); }); it('should not add disabled attribute to custom controls when disable() is called', () => { const fixture = initTest(MyInputForm, MyInput); const control = new FormControl('some value'); fixture.componentInstance.form = new FormGroup({login: control}); fixture.detectChanges(); control.disable(); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('my-input')); expect(input.nativeElement.getAttribute('disabled')).toBe(null); }); }); describe('dynamic change of FormGroup and FormArray shapes', () => { it('should handle FormControl and FormGroup swap', () => { @Component({ template: ` <form [formGroup]="form"> <input formControlName="name" id="standalone-id" *ngIf="!showAsGroup"> <ng-container formGroupName="name" *ngIf="showAsGroup"> <input formControlName="control" id="inside-group-id"> </ng-container> </form> `, standalone: false, }) class App { showAsGroup = false; form!: FormGroup; useStandaloneControl() { this.showAsGroup = false; this.form = new FormGroup({ name: new FormControl('standalone'), }); } useControlInsideGroup() { this.showAsGroup = true; this.form = new FormGroup({ name: new FormGroup({ control: new FormControl('inside-group'), }), }); } } const fixture = initTest(App); fixture.componentInstance.useStandaloneControl(); fixture.detectChanges(); let input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('standalone-id'); expect(input.value).toBe('standalone'); // Replace `FormControl` with `FormGroup` at the same location // in data model and trigger change detection. fixture.componentInstance.useControlInsideGroup(); fixture.detectChanges(); input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('inside-group-id'); expect(input.value).toBe('inside-group'); // Swap `FormGroup` with `FormControl` back at the same location // in data model and trigger change detection. fixture.componentInstance.useStandaloneControl(); fixture.detectChanges(); input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('standalone-id'); expect(input.value).toBe('standalone'); }); it('should handle FormControl and FormArray swap', () => { @Component({ template: ` <form [formGroup]="form"> <input formControlName="name" id="standalone-id" *ngIf="!showAsArray"> <ng-container formArrayName="name" *ngIf="showAsArray"> <input formControlName="0" id="inside-array-id"> </ng-container> </form> `, standalone: false, }) class App { showAsArray = false; form!: FormGroup; useStandaloneControl() { this.showAsArray = false; this.form = new FormGroup({ name: new FormControl('standalone'), }); } useControlInsideArray() { this.showAsArray = true; this.form = new FormGroup({ name: new FormArray([ new FormControl('inside-array'), // ]), }); } } const fixture = initTest(App); fixture.componentInstance.useStandaloneControl(); fixture.detectChanges(); let input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('standalone-id'); expect(input.value).toBe('standalone'); // Replace `FormControl` with `FormArray` at the same location // in data model and trigger change detection. fixture.componentInstance.useControlInsideArray(); fixture.detectChanges(); input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('inside-array-id'); expect(input.value).toBe('inside-array'); // Swap `FormArray` with `FormControl` back at the same location // in data model and trigger change detection. fixture.componentInstance.useStandaloneControl(); fixture.detectChanges(); input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('standalone-id'); expect(input.value).toBe('standalone'); }); it('should handle FormGroup and FormArray swap', () => { @Component({ template: ` <form [formGroup]="form"> <ng-container formGroupName="name" *ngIf="!showAsArray"> <input formControlName="control" id="inside-group-id"> </ng-container> <ng-container formArrayName="name" *ngIf="showAsArray"> <input formControlName="0" id="inside-array-id"> </ng-container> </form> `, standalone: false, }) class App { showAsArray = false; form!: FormGroup; useControlInsideGroup() { this.showAsArray = false; this.form = new FormGroup({ name: new FormGroup({ control: new FormControl('inside-group'), }), }); } useControlInsideArray() { this.showAsArray = true; this.form = new FormGroup({ name: new FormArray([ new FormControl('inside-array'), // ]), }); } } const fixture = initTest(App); fixture.componentInstance.useControlInsideGroup(); fixture.detectChanges(); let input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('inside-group-id'); expect(input.value).toBe('inside-group'); // Replace `FormGroup` with `FormArray` at the same location // in data model and trigger change detection. fixture.componentInstance.useControlInsideArray(); fixture.detectChanges(); input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('inside-array-id'); expect(input.value).toBe('inside-array'); // Swap `FormArray` with `FormGroup` back at the same location // in data model and trigger change detection. fixture.componentInstance.useControlInsideGroup(); fixture.detectChanges(); input = fixture.nativeElement.querySelector('input'); expect(input.id).toBe('inside-group-id'); expect(input.value).toBe('inside-group'); }); }); }); describe('user input', () => { it('should mark controls as touched after interacting with the DOM control', () => { const fixture = initTest(FormGroupComp); const login = new FormControl('oldValue'); const form = new FormGroup({'login': login}); fixture.componentInstance.form = form; fixture.detectChanges(); const loginEl = fixture.debugElement.query(By.css('input')); expect(login.touched).toBe(false); dispatchEvent(loginEl.nativeElement, 'blur'); expect(login.touched).toBe(true); }); });
{ "end_byte": 34569, "start_byte": 23936, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_34573_38063
escribe('submit and reset events', () => { it('should emit ngSubmit event with the original submit event on submit', () => { const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({'login': new FormControl('loginValue')}); fixture.componentInstance.event = null!; fixture.detectChanges(); const formEl = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(fixture.componentInstance.event.type).toEqual('submit'); }); it('should mark formGroup as submitted on submit event', () => { const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({'login': new FormControl('loginValue')}); fixture.detectChanges(); const formGroupDir = fixture.debugElement.children[0].injector.get(FormGroupDirective); expect(formGroupDir.submitted).toBe(false); const formEl = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(formGroupDir.submitted).toEqual(true); }); it('should set value in UI when form resets to that value programmatically', () => { const fixture = initTest(FormGroupComp); const login = new FormControl('some value'); const form = new FormGroup({'login': login}); fixture.componentInstance.form = form; fixture.detectChanges(); const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; expect(loginEl.value).toBe('some value'); form.reset({'login': 'reset value'}); expect(loginEl.value).toBe('reset value'); }); it('should clear value in UI when form resets programmatically', () => { const fixture = initTest(FormGroupComp); const login = new FormControl('some value'); const form = new FormGroup({'login': login}); fixture.componentInstance.form = form; fixture.detectChanges(); const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; expect(loginEl.value).toBe('some value'); form.reset(); expect(loginEl.value).toBe(''); }); }); describe('value changes and status changes', () => { it('should mark controls as dirty before emitting a value change event', () => { const fixture = initTest(FormGroupComp); const login = new FormControl('oldValue'); fixture.componentInstance.form = new FormGroup({'login': login}); fixture.detectChanges(); login.valueChanges.subscribe(() => { expect(login.dirty).toBe(true); }); const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; loginEl.value = 'newValue'; dispatchEvent(loginEl, 'input'); }); it('should mark control as pristine before emitting a value change event when resetting ', () => { const fixture = initTest(FormGroupComp); const login = new FormControl('oldValue'); const form = new FormGroup({'login': login}); fixture.componentInstance.form = form; fixture.detectChanges(); const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; loginEl.value = 'newValue'; dispatchEvent(loginEl, 'input'); expect(login.pristine).toBe(false); login.valueChanges.subscribe(() => { expect(login.pristine).toBe(true); }); form.reset(); }); });
{ "end_byte": 38063, "start_byte": 34573, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_38067_45651
escribe('unified form state change', () => { type UnwrapObservable<T> = T extends Observable<infer U> ? U : never; type ControlEvents<T extends AbstractControl> = UnwrapObservable<T['events']>[]; function expectValueChangeEvent<T>( event: ControlEvent<T> | undefined, value: T, sourceControl: AbstractControl, ) { const valueEvent = event as ValueChangeEvent<T>; expect(valueEvent).toBeInstanceOf(ValueChangeEvent); expect(valueEvent.source).toBe(sourceControl); expect(valueEvent.value).toEqual(value); } function expectPristineChangeEvent<T>( event: ControlEvent<T> | undefined, pristine: boolean, sourceControl: AbstractControl, ) { const pristineEvent = event as PristineChangeEvent; expect(pristineEvent).toBeInstanceOf(PristineChangeEvent); expect(pristineEvent.source).toBe(sourceControl); expect(pristineEvent.pristine).toBe(pristine); } function expectTouchedChangeEvent<T>( event: ControlEvent<T> | undefined, touched: boolean, sourceControl: AbstractControl, ) { const touchedEvent = event as TouchedChangeEvent; expect(touchedEvent).toBeInstanceOf(TouchedChangeEvent); expect(touchedEvent.source).toBe(sourceControl); expect(touchedEvent.touched).toBe(touched); } function expectStatusChangeEvent<T>( event: ControlEvent<T> | undefined, status: FormControlStatus, sourceControl: AbstractControl, ) { const touchedEvent = event as StatusChangeEvent; expect(touchedEvent).toBeInstanceOf(StatusChangeEvent); expect(touchedEvent.source).toBe(sourceControl); expect(touchedEvent.status).toBe(status); } it('Single level Control should emit changes for itself', () => { const fc = new FormControl<string | null>('foo', Validators.required); const values: ControlEvent[] = []; fc.events.subscribe((event) => values.push(event)); expect(values.length).toBe(0); fc.markAsTouched(); expectTouchedChangeEvent(values.at(-1), true, fc); fc.markAsUntouched(); expectTouchedChangeEvent(values.at(-1), false, fc); fc.markAsDirty(); expectPristineChangeEvent(values.at(-1), false, fc); fc.markAsPristine(); expectPristineChangeEvent(values.at(-1), true, fc); fc.disable(); expectValueChangeEvent(values.at(-2), 'foo', fc); expectStatusChangeEvent(values.at(-1), 'DISABLED', fc); expect(values.length).toBe(6); fc.enable(); expectValueChangeEvent(values.at(-2), 'foo', fc); expectStatusChangeEvent(values.at(-1), 'VALID', fc); expect(values.length).toBe(8); fc.setValue(null); expectValueChangeEvent(values.at(-2), null, fc); expectStatusChangeEvent(values.at(-1), 'INVALID', fc); expect(values.length).toBe(10); // setValue doesnt emit dirty or touched fc.setValue('bar'); expectValueChangeEvent(values.at(-2), 'bar', fc); expectStatusChangeEvent(values.at(-1), 'VALID', fc); expect(values.length).toBe(12); const subject = new Subject<string>(); const asyncValidator = () => subject.pipe(map(() => null)); fc.addAsyncValidators(asyncValidator); fc.updateValueAndValidity(); // Value is emitted because of updateValueAndValidity expectValueChangeEvent(values.at(-2), 'bar', fc); expectStatusChangeEvent(values.at(-1), 'PENDING', fc); subject.next(''); subject.complete(); expectStatusChangeEvent(values.at(-1), 'VALID', fc); expect(values.length).toBe(15); }); it('should not emit twice the same value', () => { const fc = new FormControl<string | null>('foo', Validators.required); const fcEvents: ControlEvent<string | null>[] = []; fc.events.subscribe((event) => fcEvents.push(event)); expect(fcEvents.length).toBe(0); fc.markAsDirty(); fc.markAsDirty(); expect(fcEvents.length).toBe(1); fc.markAsPristine(); fc.markAsPristine(); expect(fcEvents.length).toBe(2); fc.markAsTouched(); fc.markAsTouched(); expect(fcEvents.length).toBe(3); fc.markAsUntouched(); fc.markAsUntouched(); expect(fcEvents.length).toBe(4); }); it('Nested formControl should emit changes for itself and its parent', () => { const fc1 = new FormControl<string | null>('foo', Validators.required); const fc2 = new FormControl<string | null>('bar', Validators.required); const fg = new FormGroup({fc1, fc2}); const fc1Events: ControlEvent<string | null>[] = []; const fc2Events: ControlEvent<string | null>[] = []; const fgEvents: ControlEvent<Partial<{fc1: string | null; fc2: string | null}>>[] = []; fc1.events.subscribe((event) => fc1Events.push(event)); fc2.events.subscribe((event) => fc2Events.push(event)); fg.events.subscribe((event) => fgEvents.push(event)); fc1.setValue('bar'); expectValueChangeEvent(fc1Events.at(-2), 'bar', fc1); expectStatusChangeEvent(fc1Events.at(-1), 'VALID', fc1); expect(fc1Events.length).toBe(2); expectValueChangeEvent(fgEvents.at(-2), {fc1: 'bar', fc2: 'bar'}, fc1); expectStatusChangeEvent(fgEvents.at(-1), 'VALID', fc1); }); it('Nested formControl children should emit pristine', () => { const fc1 = new FormControl<string | null>('foo', Validators.required); const fc2 = new FormControl<string | null>('bar', Validators.required); const fg = new FormGroup({fc1, fc2}); const fc1Event: ControlEvents<typeof fc1> = []; const fc2Event: ControlEvents<typeof fc2> = []; const fgEvent: ControlEvents<typeof fg> = []; fc1.events.subscribe((event) => fc1Event.push(event)); fc2.events.subscribe((event) => fc2Event.push(event)); fg.events.subscribe((event) => fgEvent.push(event)); fc1.markAsDirty(); expect(fc1Event.length).toBe(1); expect(fc2Event.length).toBe(0); expect(fgEvent.length).toBe(1); fg.markAsPristine(); // Marking children as pristine does not emit an event on the parent // Source control is itself expectPristineChangeEvent(fgEvent.at(-1), true, fg); expect(fgEvent.length).toBe(2); // Child that was dirty emits a pristine change // Source control is itself, as even are only bubbled up expectPristineChangeEvent(fc1Event.at(-1), true, fc1); expect(fc1Event.length).toBe(2); // This child was already pristine, it doesn't emit a pristine change expect(fc2Event.length).toBe(0); }); it('Nested formControl should emit dirty', () => { const fc1 = new FormControl<string | null>('foo', Validators.required); const fc2 = new FormControl<string | null>('bar', Validators.required); const fg = new FormGroup({fc1, fc2}); const fc1Events: ControlEvents<typeof fc1> = []; const fc2Events: ControlEvents<typeof fc2> = []; const fgEvents: ControlEvents<typeof fg> = []; fc1.events.subscribe((event) => fc1Events.push(event)); fc2.events.subscribe((event) => fc2Events.push(event)); fg.events.subscribe((event) => fgEvents.push(event)); fc1.markAsDirty(); expect(fc1Events.length).toBe(1); expect(fgEvents.length).toBe(1); expect(fc2Events.length).toBe(0); // sourceControl is the child control expectPristineChangeEvent(fgEvents.at(-1), false, fc1); expectPristineChangeEvent(fc1Events.at(-1), false, fc1); });
{ "end_byte": 45651, "start_byte": 38067, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_45657_52126
t('Nested formControl should emit touched', () => { const fc1 = new FormControl<string | null>('foo', Validators.required); const fc2 = new FormControl<string | null>('bar', Validators.required); const fg = new FormGroup({fc1, fc2}); const fc1Events: ControlEvent[] = []; const fc2Events: ControlEvent[] = []; const fgEvents: ControlEvent[] = []; fc1.events.subscribe((event) => fc1Events.push(event)); fc2.events.subscribe((event) => fc2Events.push(event)); fg.events.subscribe((event) => fgEvents.push(event)); fc1.markAsTouched(); expect(fc1Events.length).toBe(1); expect(fgEvents.length).toBe(1); expect(fc2Events.length).toBe(0); // sourceControl is the child control expectTouchedChangeEvent(fgEvents.at(-1), true, fc1); expectTouchedChangeEvent(fc1Events.at(-1), true, fc1); }); it('Nested formControl should emit disabled', () => { const fc1 = new FormControl<string | null>('foo', Validators.required); const fc2 = new FormControl<string | null>('bar', Validators.required); const fg = new FormGroup({fc1, fc2}); const fc1Events: ControlEvent[] = []; const fc2Events: ControlEvent[] = []; const fgEvents: ControlEvent[] = []; fc1.events.subscribe((event) => fc1Events.push(event)); fc2.events.subscribe((event) => fc2Events.push(event)); fg.events.subscribe((event) => fgEvents.push(event)); expect(fg.pristine).toBeTrue(); fc1.disable(); expect(fc1Events.length).toBe(2); expect(fgEvents.length).toBe(3); expect(fc2Events.length).toBe(0); expectValueChangeEvent(fgEvents.at(-3), {fc2: 'bar'}, fg); expectStatusChangeEvent(fgEvents.at(-2), 'VALID', fg); expectTouchedChangeEvent(fgEvents.at(-1), false, fc1); // No prisitine event sent as fg was already pristine expectValueChangeEvent(fc1Events.at(-2), 'foo', fc1); expectStatusChangeEvent(fc1Events.at(-1), 'DISABLED', fc1); }); it('Nested formControl should emit PENDING', () => { const fc1 = new FormControl<string | null>('foo', Validators.required); const fc2 = new FormControl<string | null>('bar', Validators.required); const fg = new FormGroup({fc1, fc2}); const fc1Events: ControlEvent[] = []; const fc2Events: ControlEvent[] = []; const fgEvents: ControlEvent[] = []; fc1.events.subscribe((event) => fc1Events.push(event)); fc2.events.subscribe((event) => fc2Events.push(event)); fg.events.subscribe((event) => fgEvents.push(event)); fc1.markAsPending(); expectStatusChangeEvent(fgEvents.at(-1), 'PENDING', fc1); expectStatusChangeEvent(fc1Events.at(-1), 'PENDING', fc1); expect(fc1Events.length).toBe(1); expect(fgEvents.length).toBe(1); expect(fc2Events.length).toBe(0); // Reseting to VALID fc1.updateValueAndValidity(); expectValueChangeEvent(fgEvents.at(-2), {fc1: 'foo', fc2: 'bar'}, fc1); expectStatusChangeEvent(fgEvents.at(-1), 'VALID', fc1); expectValueChangeEvent(fc1Events.at(-2), 'foo', fc1); expectStatusChangeEvent(fc1Events.at(-1), 'VALID', fc1); expect(fc1Events.length).toBe(3); expect(fgEvents.length).toBe(3); expect(fc2Events.length).toBe(0); // Triggering PENDING again with the async validator now const subject = new Subject<string>(); const asyncValidator = () => subject.pipe(map(() => null)); fc1.addAsyncValidators(asyncValidator); fc1.updateValueAndValidity(); expect(fc1Events.length).toBe(5); expect(fgEvents.length).toBe(5); expect(fc2Events.length).toBe(0); expectValueChangeEvent(fgEvents.at(-2), {fc1: 'foo', fc2: 'bar'}, fc1); expectStatusChangeEvent(fgEvents.at(-1), 'PENDING', fc1); expectValueChangeEvent(fc1Events.at(-2), 'foo', fc1); expectStatusChangeEvent(fc1Events.at(-1), 'PENDING', fc1); subject.next(''); subject.complete(); expectStatusChangeEvent(fgEvents.at(-1), 'VALID', fc1); expectStatusChangeEvent(fc1Events.at(-1), 'VALID', fc1); }); it('formControl should not emit when emitEvent is false', () => { const fc = new FormControl<string | null>('foo', Validators.required); const fcEvents: ControlEvent[] = []; fc.events.subscribe((event) => fcEvents.push(event)); expect(fcEvents.length).toBe(0); fc.markAsTouched({emitEvent: false}); expect(fcEvents.length).toBe(0); fc.markAllAsTouched({emitEvent: false}); expect(fcEvents.length).toBe(0); fc.markAsUntouched({emitEvent: false}); expect(fcEvents.length).toBe(0); fc.markAsPristine({emitEvent: false}); expect(fcEvents.length).toBe(0); fc.markAsDirty({emitEvent: false}); expect(fcEvents.length).toBe(0); }); it('formControl should emit an event when resetting a form', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('', Validators.required)}); fixture.componentInstance.form = form; fixture.detectChanges(); const formGroupDir = fixture.debugElement.children[0].injector.get(FormGroupDirective); const events: ControlEvent[] = []; fixture.componentInstance.form.events.subscribe((event) => events.push(event)); formGroupDir.resetForm(); expect(events.length).toBe(4); expect(events[0]).toBeInstanceOf(TouchedChangeEvent); expect(events[1]).toBeInstanceOf(ValueChangeEvent); expect(events[2]).toBeInstanceOf(StatusChangeEvent); // The event that matters expect(events[3]).toBeInstanceOf(FormResetEvent); expect(events[3].source).toBe(form); }); it('formControl should emit an event when submitting a form', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('', Validators.required)}); fixture.componentInstance.form = form; fixture.detectChanges(); const formGroupDir = fixture.debugElement.children[0].injector.get(FormGroupDirective); const events: ControlEvent[] = []; fixture.componentInstance.form.events.subscribe((event) => events.push(event)); formGroupDir.onSubmit({} as any); expect(events.length).toBe(1); expect(events[0]).toBeInstanceOf(FormSubmittedEvent); expect(events[0].source).toBe(form); }); });
{ "end_byte": 52126, "start_byte": 45657, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_52130_60915
escribe('setting status classes', () => { it('should not assign status on standalone <form> element', () => { @Component({ selector: 'form-comp', template: ` <form></form> `, standalone: false, }) class FormComp {} const fixture = initReactiveFormsTest(FormComp); fixture.detectChanges(); const form = fixture.debugElement.query(By.css('form')).nativeElement; // Expect no classes added to the <form> element since it has no // reactive directives attached and only ReactiveForms module is used. expect(sortedClassList(form)).toEqual([]); }); it('should not assign status on standalone <form> element with form control inside', () => { @Component({ selector: 'form-comp', template: ` <form> <input type="text" [formControl]="control"> </form> `, standalone: false, }) class FormComp { control = new FormControl('abc'); } const fixture = initReactiveFormsTest(FormComp); fixture.detectChanges(); const form = fixture.debugElement.query(By.css('form')).nativeElement; // Expect no classes added to the <form> element since it has no // reactive directives attached and only ReactiveForms module is used. expect(sortedClassList(form)).toEqual([]); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(sortedClassList(input)).toEqual(['ng-pristine', 'ng-untouched', 'ng-valid']); }); it('should work with single fields', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', Validators.required); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); input.value = 'updatedValue'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); }); it('should work with single fields and async validators', fakeAsync(() => { const fixture = initTest(FormControlComp); const control = new FormControl('', null!, uniqLoginAsyncValidator('good')); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(sortedClassList(input)).toEqual(['ng-pending', 'ng-pristine', 'ng-untouched']); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-pending', 'ng-pristine', 'ng-touched']); input.value = 'good'; dispatchEvent(input, 'input'); tick(); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); })); it('should work with single fields that combines async and sync validators', fakeAsync(() => { const fixture = initTest(FormControlComp); const control = new FormControl('', Validators.required, uniqLoginAsyncValidator('good')); fixture.debugElement.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); input.value = 'bad'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-pending', 'ng-touched']); tick(); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-invalid', 'ng-touched']); input.value = 'good'; dispatchEvent(input, 'input'); tick(); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); })); it('should work with single fields in parent forms', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('', Validators.required)}); fixture.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const formEl = fixture.debugElement.query(By.css('form')).nativeElement; expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); input.value = 'updatedValue'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(sortedClassList(input)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).toContain('ng-submitted'); dispatchEvent(formEl, 'reset'); fixture.detectChanges(); expect(sortedClassList(input)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); }); it('should work with formGroup', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('', Validators.required)}); fixture.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const formEl = fixture.debugElement.query(By.css('form')).nativeElement; expect(sortedClassList(formEl)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(sortedClassList(formEl)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']); input.value = 'updatedValue'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(sortedClassList(formEl)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']); dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(sortedClassList(formEl)).toContain('ng-submitted'); dispatchEvent(formEl, 'reset'); fixture.detectChanges(); expect(sortedClassList(input)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); }); it('should not assign `ng-submitted` class to elements with `formArrayName`', () => { // Since element with the `formArrayName` can not represent top-level forms (can only be // inside other elements), this test verifies that these elements never receive // `ng-submitted` CSS class even when they are located inside submitted form. const fixture = initTest(FormArrayComp); const cityArray = new FormArray([new FormControl('SF'), new FormControl('NY')]); const form = new FormGroup({cities: cityArray}); fixture.componentInstance.form = form; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const [loginInput, passwordInput] = fixture.debugElement .queryAll(By.css('input')) .map((el) => el.nativeElement); const arrEl = fixture.debugElement.query(By.css('div')).nativeElement; const formEl = fixture.debugElement.query(By.css('form')).nativeElement; expect(passwordInput).toBeDefined(); expect(sortedClassList(loginInput)).not.toContain('ng-submitted'); expect(sortedClassList(arrEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(sortedClassList(loginInput)).not.toContain('ng-submitted'); expect(sortedClassList(arrEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).toContain('ng-submitted'); dispatchEvent(formEl, 'reset'); fixture.detectChanges(); expect(sortedClassList(loginInput)).not.toContain('ng-submitted'); expect(sortedClassList(arrEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); });
{ "end_byte": 60915, "start_byte": 52130, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_60921_64160
t('should apply submitted status with nested formArrayName', () => { const fixture = initTest(NestedFormArrayNameComp); const ic = new FormControl('foo'); const arr = new FormArray([ic]); const form = new FormGroup({arr}); fixture.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const arrEl = fixture.debugElement.query(By.css('div')).nativeElement; const formEl = fixture.debugElement.query(By.css('form')).nativeElement; expect(sortedClassList(input)).not.toContain('ng-submitted'); expect(sortedClassList(arrEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(sortedClassList(input)).not.toContain('ng-submitted'); expect(sortedClassList(arrEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).toContain('ng-submitted'); dispatchEvent(formEl, 'reset'); fixture.detectChanges(); expect(sortedClassList(input)).not.toContain('ng-submitted'); expect(sortedClassList(arrEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); }); it('should apply submitted status with nested formGroupName', () => { const fixture = initTest(NestedFormGroupNameComp); const loginControl = new FormControl('', { validators: Validators.required, updateOn: 'change', }); const passwordControl = new FormControl('', Validators.required); const formGroup = new FormGroup( {signin: new FormGroup({login: loginControl, password: passwordControl})}, {updateOn: 'blur'}, ); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const [loginInput, passwordInput] = fixture.debugElement .queryAll(By.css('input')) .map((el) => el.nativeElement); const formEl = fixture.debugElement.query(By.css('form')).nativeElement; const groupEl = fixture.debugElement.query(By.css('div')).nativeElement; loginInput.value = 'Nancy'; // Input and blur events, as in a real interaction, cause the form to be touched and // dirtied. dispatchEvent(loginInput, 'input'); dispatchEvent(loginInput, 'blur'); fixture.detectChanges(); expect(sortedClassList(loginInput)).not.toContain('ng-submitted'); expect(sortedClassList(groupEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); dispatchEvent(formEl, 'submit'); fixture.detectChanges(); expect(sortedClassList(loginInput)).not.toContain('ng-submitted'); expect(sortedClassList(groupEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).toContain('ng-submitted'); dispatchEvent(formEl, 'reset'); fixture.detectChanges(); expect(sortedClassList(loginInput)).not.toContain('ng-submitted'); expect(sortedClassList(groupEl)).not.toContain('ng-submitted'); expect(sortedClassList(formEl)).not.toContain('ng-submitted'); }); });
{ "end_byte": 64160, "start_byte": 60921, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_64164_74077
escribe('updateOn options', () => { describe('on blur', () => { it('should not update value or validity based on user input until blur', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', {validators: Validators.required, updateOn: 'blur'}); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until blur.') .toEqual(''); expect(control.valid) .withContext('Expected no validation to occur until blur.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to change once control is blurred.') .toEqual('Nancy'); expect(control.valid) .withContext('Expected validation to run once control is blurred.') .toBe(true); }); it('should not update parent group value/validity from child until blur', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({ login: new FormControl('', {validators: Validators.required, updateOn: 'blur'}), }); fixture.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(form.value) .withContext('Expected group value to remain unchanged until blur.') .toEqual({login: ''}); expect(form.valid) .withContext('Expected no validation to occur on group until blur.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(form.value) .withContext('Expected group value to change once input blurred.') .toEqual({login: 'Nancy'}); expect(form.valid).withContext('Expected validation to run once input blurred.').toBe(true); }); it('should not wait for blur event to update if value is set programmatically', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', {validators: Validators.required, updateOn: 'blur'}); fixture.componentInstance.control = control; fixture.detectChanges(); control.setValue('Nancy'); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input.value) .withContext('Expected value to propagate to view immediately.') .toEqual('Nancy'); expect(control.value) .withContext('Expected model value to update immediately.') .toEqual('Nancy'); expect(control.valid).withContext('Expected validation to run immediately.').toBe(true); }); it('should not update dirty state until control is blurred', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', {updateOn: 'blur'}); fixture.componentInstance.control = control; fixture.detectChanges(); expect(control.dirty).withContext('Expected control to start out pristine.').toBe(false); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.dirty) .withContext('Expected control to stay pristine until blurred.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.dirty) .withContext('Expected control to update dirty state when blurred.') .toBe(true); }); it('should update touched when control is blurred', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', {updateOn: 'blur'}); fixture.componentInstance.control = control; fixture.detectChanges(); expect(control.touched).withContext('Expected control to start out untouched.').toBe(false); const input = fixture.debugElement.query(By.css('input')).nativeElement; dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.touched) .withContext('Expected control to update touched state when blurred.') .toBe(true); }); it('should continue waiting for blur to update if previously blurred', () => { const fixture = initTest(FormControlComp); const control = new FormControl('Nancy', { validators: Validators.required, updateOn: 'blur', }); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; dispatchEvent(input, 'blur'); fixture.detectChanges(); dispatchEvent(input, 'focus'); input.value = ''; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until second blur.') .toEqual('Nancy'); expect(control.valid) .withContext('Expected validation not to run until second blur.') .toBe(true); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to update when blur occurs again.') .toEqual(''); expect(control.valid) .withContext('Expected validation to run when blur occurs again.') .toBe(false); }); it('should not use stale pending value if value set programmatically', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', {validators: Validators.required, updateOn: 'blur'}); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'aa'; dispatchEvent(input, 'input'); fixture.detectChanges(); control.setValue('Nancy'); fixture.detectChanges(); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(input.value) .withContext('Expected programmatic value to stick after blur.') .toEqual('Nancy'); }); it('should set initial value and validity on init', () => { const fixture = initTest(FormControlComp); const control = new FormControl('Nancy', { validators: Validators.maxLength(3), updateOn: 'blur', }); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input.value).withContext('Expected value to be set in the view.').toEqual('Nancy'); expect(control.value) .withContext('Expected initial model value to be set.') .toEqual('Nancy'); expect(control.valid) .withContext('Expected validation to run on initial value.') .toBe(false); }); it('should reset properly', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', {validators: Validators.required, updateOn: 'blur'}); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'aa'; dispatchEvent(input, 'input'); fixture.detectChanges(); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.dirty).withContext('Expected control to be dirty on blur.').toBe(true); control.reset(); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(input.value).withContext('Expected view value to reset').toEqual(''); expect(control.value).withContext('Expected pending value to reset.').toBe(null); expect(control.dirty).withContext('Expected pending dirty value to reset.').toBe(false); }); it('should be able to remove a control as a result of another control being reset', () => { @Component({ template: ` <form [formGroup]="form"> <input formControlName="name"> <input formControlName="surname"> </form> `, standalone: false, }) class App implements OnDestroy { private _subscription: Subscription; form: FormGroup = new FormGroup({ name: new FormControl('Frodo'), surname: new FormControl('Baggins'), }); constructor() { this._subscription = this.form.controls['name'].valueChanges.subscribe((value) => { if (!value) { this.form.removeControl('surname'); } }); } ngOnDestroy() { this._subscription.unsubscribe(); } } const fixture = initTest(App); fixture.detectChanges(); expect(fixture.componentInstance.form.value).toEqual({name: 'Frodo', surname: 'Baggins'}); expect(() => { fixture.componentInstance.form.reset(); fixture.detectChanges(); }).not.toThrow(); expect(fixture.componentInstance.form.value).toEqual({name: null}); });
{ "end_byte": 74077, "start_byte": 64164, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_74085_82305
t('should not emit valueChanges or statusChanges until blur', () => { const fixture = initTest(FormControlComp); const control: FormControl = new FormControl('', { validators: Validators.required, updateOn: 'blur', }); fixture.componentInstance.control = control; fixture.detectChanges(); const values: string[] = []; const sub = merge(control.valueChanges, control.statusChanges).subscribe((val) => values.push(val), ); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges on input.') .toEqual([]); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values) .withContext('Expected valueChanges and statusChanges on blur.') .toEqual(['Nancy', 'VALID']); sub.unsubscribe(); }); it('should not emit valueChanges or statusChanges on blur if value unchanged', () => { const fixture = initTest(FormControlComp); const control: FormControl = new FormControl('', { validators: Validators.required, updateOn: 'blur', }); fixture.componentInstance.control = control; fixture.detectChanges(); const values: string[] = []; const sub = merge(control.valueChanges, control.statusChanges).subscribe((val) => values.push(val), ); const input = fixture.debugElement.query(By.css('input')).nativeElement; dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges if value unchanged.') .toEqual([]); input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges on input.') .toEqual([]); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID'], 'Expected valueChanges and statusChanges on blur if value changed.', ); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID'], 'Expected valueChanges and statusChanges not to fire again on blur unless value changed.', ); input.value = 'Bess'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID'], 'Expected valueChanges and statusChanges not to fire on input after blur.', ); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID', 'Bess', 'VALID'], 'Expected valueChanges and statusChanges to fire again on blur if value changed.', ); sub.unsubscribe(); }); it('should mark as pristine properly if pending dirty', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', {updateOn: 'blur'}); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'aa'; dispatchEvent(input, 'input'); fixture.detectChanges(); dispatchEvent(input, 'blur'); fixture.detectChanges(); control.markAsPristine(); expect(control.dirty).withContext('Expected control to become pristine.').toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.dirty).withContext('Expected pending dirty value to reset.').toBe(false); }); it('should update on blur with group updateOn', () => { const fixture = initTest(FormGroupComp); const control = new FormControl('', Validators.required); const formGroup = new FormGroup({login: control}, {updateOn: 'blur'}); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until blur.') .toEqual(''); expect(control.valid) .withContext('Expected no validation to occur until blur.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to change once control is blurred.') .toEqual('Nancy'); expect(control.valid) .withContext('Expected validation to run once control is blurred.') .toBe(true); }); it('should update on blur with array updateOn', () => { const fixture = initTest(FormArrayComp); const control = new FormControl('', Validators.required); const cityArray = new FormArray([control], {updateOn: 'blur'}); const formGroup = new FormGroup({cities: cityArray}); fixture.componentInstance.form = formGroup; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until blur.') .toEqual(''); expect(control.valid) .withContext('Expected no validation to occur until blur.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to change once control is blurred.') .toEqual('Nancy'); expect(control.valid) .withContext('Expected validation to run once control is blurred.') .toBe(true); }); it('should allow child control updateOn blur to override group updateOn', () => { const fixture = initTest(NestedFormGroupNameComp); const loginControl = new FormControl('', { validators: Validators.required, updateOn: 'change', }); const passwordControl = new FormControl('', Validators.required); const formGroup = new FormGroup( {signin: new FormGroup({login: loginControl, password: passwordControl})}, {updateOn: 'blur'}, ); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const [loginInput, passwordInput] = fixture.debugElement.queryAll(By.css('input')); loginInput.nativeElement.value = 'Nancy'; dispatchEvent(loginInput.nativeElement, 'input'); fixture.detectChanges(); expect(loginControl.value).withContext('Expected value change on input.').toEqual('Nancy'); expect(loginControl.valid).withContext('Expected validation to run on input.').toBe(true); passwordInput.nativeElement.value = 'Carson'; dispatchEvent(passwordInput.nativeElement, 'input'); fixture.detectChanges(); expect(passwordControl.value) .withContext('Expected value to remain unchanged until blur.') .toEqual(''); expect(passwordControl.valid) .withContext('Expected no validation to occur until blur.') .toBe(false); dispatchEvent(passwordInput.nativeElement, 'blur'); fixture.detectChanges(); expect(passwordControl.value) .withContext('Expected value to change once control is blurred.') .toEqual('Carson'); expect(passwordControl.valid) .withContext('Expected validation to run once control is blurred.') .toBe(true); }); });
{ "end_byte": 82305, "start_byte": 74085, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_82311_91945
escribe('on submit', () => { it('should set initial value and validity on init', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({ login: new FormControl('Nancy', {validators: Validators.required, updateOn: 'submit'}), }); fixture.componentInstance.form = form; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input.value) .withContext('Expected initial value to propagate to view.') .toEqual('Nancy'); expect(form.value).withContext('Expected initial value to be set.').toEqual({ login: 'Nancy', }); expect(form.valid) .withContext('Expected form to run validation on initial value.') .toBe(true); }); it('should not update value or validity until submit', () => { const fixture = initTest(FormGroupComp); const formGroup = new FormGroup({ login: new FormControl('', {validators: Validators.required, updateOn: 'submit'}), }); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(formGroup.value) .withContext('Expected form value to remain unchanged on input.') .toEqual({login: ''}); expect(formGroup.valid) .withContext('Expected form validation not to run on input.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(formGroup.value) .withContext('Expected form value to remain unchanged on blur.') .toEqual({login: ''}); expect(formGroup.valid) .withContext('Expected form validation not to run on blur.') .toBe(false); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(formGroup.value).withContext('Expected form value to update on submit.').toEqual({ login: 'Nancy', }); expect(formGroup.valid) .withContext('Expected form validation to run on submit.') .toBe(true); }); it('should not update after submit until a second submit', () => { const fixture = initTest(FormGroupComp); const formGroup = new FormGroup({ login: new FormControl('', {validators: Validators.required, updateOn: 'submit'}), }); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); input.value = ''; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(formGroup.value) .withContext('Expected value not to change until a second submit.') .toEqual({login: 'Nancy'}); expect(formGroup.valid) .withContext('Expected validation not to run until a second submit.') .toBe(true); dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(formGroup.value) .withContext('Expected value to update on the second submit.') .toEqual({login: ''}); expect(formGroup.valid) .withContext('Expected validation to run on a second submit.') .toBe(false); }); it('should not wait for submit to set value programmatically', () => { const fixture = initTest(FormGroupComp); const formGroup = new FormGroup({ login: new FormControl('', {validators: Validators.required, updateOn: 'submit'}), }); fixture.componentInstance.form = formGroup; fixture.detectChanges(); formGroup.setValue({login: 'Nancy'}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input.value) .withContext('Expected view value to update immediately.') .toEqual('Nancy'); expect(formGroup.value).withContext('Expected form value to update immediately.').toEqual({ login: 'Nancy', }); expect(formGroup.valid) .withContext('Expected form validation to run immediately.') .toBe(true); }); it('should not update dirty until submit', () => { const fixture = initTest(FormGroupComp); const formGroup = new FormGroup({login: new FormControl('', {updateOn: 'submit'})}); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(formGroup.dirty).withContext('Expected dirty not to change on input.').toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(formGroup.dirty).withContext('Expected dirty not to change on blur.').toBe(false); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(formGroup.dirty).withContext('Expected dirty to update on submit.').toBe(true); }); it('should not update touched until submit', () => { const fixture = initTest(FormGroupComp); const formGroup = new FormGroup({login: new FormControl('', {updateOn: 'submit'})}); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(formGroup.touched) .withContext('Expected touched not to change until submit.') .toBe(false); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(formGroup.touched).withContext('Expected touched to update on submit.').toBe(true); }); it('should reset properly', () => { const fixture = initTest(FormGroupComp); const formGroup = new FormGroup({ login: new FormControl('', {validators: Validators.required, updateOn: 'submit'}), }); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); dispatchEvent(input, 'blur'); fixture.detectChanges(); formGroup.reset(); fixture.detectChanges(); expect(input.value).withContext('Expected view value to reset.').toEqual(''); expect(formGroup.value).withContext('Expected form value to reset').toEqual({login: null}); expect(formGroup.dirty).withContext('Expected dirty to stay false on reset.').toBe(false); expect(formGroup.touched) .withContext('Expected touched to stay false on reset.') .toBe(false); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(formGroup.value).withContext('Expected form value to stay empty on submit').toEqual({ login: null, }); expect(formGroup.dirty).withContext('Expected dirty to stay false on submit.').toBe(false); expect(formGroup.touched) .withContext('Expected touched to stay false on submit.') .toBe(false); }); it('should not emit valueChanges or statusChanges until submit', () => { const fixture = initTest(FormGroupComp); const control = new FormControl('', {validators: Validators.required, updateOn: 'submit'}); const formGroup = new FormGroup({login: control}); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const values: any[] = []; const streams = merge( control.valueChanges, control.statusChanges, formGroup.valueChanges, formGroup.statusChanges, ); const sub = streams.subscribe((val) => values.push(val)); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges on input') .toEqual([]); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values).withContext('Expected no valueChanges or statusChanges on blur').toEqual([]); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID', {login: 'Nancy'}, 'VALID'], 'Expected valueChanges and statusChanges to update on submit.', ); sub.unsubscribe(); });
{ "end_byte": 91945, "start_byte": 82311, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_91953_101392
t('should not emit valueChanges or statusChanges on submit if value unchanged', () => { const fixture = initTest(FormGroupComp); const control = new FormControl('', {validators: Validators.required, updateOn: 'submit'}); const formGroup = new FormGroup({login: control}); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const values: any[] = []; const streams = merge( control.valueChanges, control.statusChanges, formGroup.valueChanges, formGroup.statusChanges, ); const sub = streams.subscribe((val) => values.push(val)); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges if value unchanged.') .toEqual([]); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges on input.') .toEqual([]); dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID', {login: 'Nancy'}, 'VALID'], 'Expected valueChanges and statusChanges on submit if value changed.', ); dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID', {login: 'Nancy'}, 'VALID'], 'Expected valueChanges and statusChanges not to fire again if value unchanged.', ); input.value = 'Bess'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID', {login: 'Nancy'}, 'VALID'], 'Expected valueChanges and statusChanges not to fire on input after submit.', ); dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID', {login: 'Nancy'}, 'VALID', 'Bess', 'VALID', {login: 'Bess'}, 'VALID'], 'Expected valueChanges and statusChanges to fire again on submit if value changed.', ); sub.unsubscribe(); }); it('should not run validation for onChange controls on submit', () => { const validatorSpy = jasmine.createSpy('validator'); const groupValidatorSpy = jasmine.createSpy('groupValidatorSpy'); const fixture = initTest(NestedFormGroupNameComp); const formGroup = new FormGroup({ signin: new FormGroup({login: new FormControl(), password: new FormControl()}), email: new FormControl('', {updateOn: 'submit'}), }); fixture.componentInstance.form = formGroup; fixture.detectChanges(); formGroup.get('signin.login')!.setValidators(validatorSpy); formGroup.get('signin')!.setValidators(groupValidatorSpy); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(validatorSpy).not.toHaveBeenCalled(); expect(groupValidatorSpy).not.toHaveBeenCalled(); }); it('should mark as untouched properly if pending touched', () => { const fixture = initTest(FormGroupComp); const formGroup = new FormGroup({login: new FormControl('', {updateOn: 'submit'})}); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; dispatchEvent(input, 'blur'); fixture.detectChanges(); formGroup.markAsUntouched(); fixture.detectChanges(); expect(formGroup.touched).withContext('Expected group to become untouched.').toBe(false); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(formGroup.touched) .withContext('Expected touched to stay false on submit.') .toBe(false); }); it('should update on submit with group updateOn', () => { const fixture = initTest(FormGroupComp); const control = new FormControl('', Validators.required); const formGroup = new FormGroup({login: control}, {updateOn: 'submit'}); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until submit.') .toEqual(''); expect(control.valid) .withContext('Expected no validation to occur until submit.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until submit.') .toEqual(''); expect(control.valid) .withContext('Expected no validation to occur until submit.') .toBe(false); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(control.value).withContext('Expected value to change on submit.').toEqual('Nancy'); expect(control.valid).withContext('Expected validation to run on submit.').toBe(true); }); it('should update on submit with array updateOn', () => { const fixture = initTest(FormArrayComp); const control = new FormControl('', Validators.required); const cityArray = new FormArray([control], {updateOn: 'submit'}); const formGroup = new FormGroup({cities: cityArray}); fixture.componentInstance.form = formGroup; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until submit.') .toEqual(''); expect(control.valid) .withContext('Expected no validation to occur until submit.') .toBe(false); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to change once control on submit') .toEqual('Nancy'); expect(control.valid).withContext('Expected validation to run on submit.').toBe(true); }); it('should allow child control updateOn submit to override group updateOn', () => { const fixture = initTest(NestedFormGroupNameComp); const loginControl = new FormControl('', { validators: Validators.required, updateOn: 'change', }); const passwordControl = new FormControl('', Validators.required); const formGroup = new FormGroup( {signin: new FormGroup({login: loginControl, password: passwordControl})}, {updateOn: 'submit'}, ); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const [loginInput, passwordInput] = fixture.debugElement.queryAll(By.css('input')); loginInput.nativeElement.value = 'Nancy'; dispatchEvent(loginInput.nativeElement, 'input'); fixture.detectChanges(); expect(loginControl.value).withContext('Expected value change on input.').toEqual('Nancy'); expect(loginControl.valid).withContext('Expected validation to run on input.').toBe(true); passwordInput.nativeElement.value = 'Carson'; dispatchEvent(passwordInput.nativeElement, 'input'); fixture.detectChanges(); expect(passwordControl.value) .withContext('Expected value to remain unchanged until submit.') .toEqual(''); expect(passwordControl.valid) .withContext('Expected no validation to occur until submit.') .toBe(false); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); expect(passwordControl.value) .withContext('Expected value to change on submit.') .toEqual('Carson'); expect(passwordControl.valid) .withContext('Expected validation to run on submit.') .toBe(true); }); it('should not prevent the default action on forms with method="dialog"', fakeAsync(() => { if (typeof HTMLDialogElement === 'undefined') { return; } const fixture = initTest(NativeDialogForm); fixture.detectChanges(); tick(); const event = dispatchEvent(fixture.componentInstance.form.nativeElement, 'submit'); fixture.detectChanges(); expect(event.defaultPrevented).toBe(false); })); }); });
{ "end_byte": 101392, "start_byte": 91953, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_101396_107753
escribe('ngModel interactions', () => { let warnSpy: jasmine.Spy; beforeEach(() => { // Reset `_ngModelWarningSentOnce` on `FormControlDirective` and `FormControlName` types. (FormControlDirective as any)._ngModelWarningSentOnce = false; (FormControlName as any)._ngModelWarningSentOnce = false; warnSpy = spyOn(console, 'warn'); }); describe('deprecation warnings', () => { it('should warn once by default when using ngModel with formControlName', fakeAsync(() => { const fixture = initTest(FormGroupNgModel); fixture.componentInstance.form = new FormGroup({ 'login': new FormControl(''), 'password': new FormControl(''), }); fixture.detectChanges(); tick(); expect(warnSpy.calls.count()).toEqual(1); expect(warnSpy.calls.mostRecent().args[0]).toMatch( /It looks like you're using ngModel on the same form field as formControlName/gi, ); fixture.componentInstance.login = 'some value'; fixture.detectChanges(); tick(); expect(warnSpy.calls.count()).toEqual(1); })); it('should warn once by default when using ngModel with formControl', fakeAsync(() => { const fixture = initTest(FormControlNgModel); fixture.componentInstance.control = new FormControl(''); fixture.componentInstance.passwordControl = new FormControl(''); fixture.detectChanges(); tick(); expect(warnSpy.calls.count()).toEqual(1); expect(warnSpy.calls.mostRecent().args[0]).toMatch( /It looks like you're using ngModel on the same form field as formControl/gi, ); fixture.componentInstance.login = 'some value'; fixture.detectChanges(); tick(); expect(warnSpy.calls.count()).toEqual(1); })); it('should warn once for each instance when global provider is provided with "always"', fakeAsync(() => { TestBed.configureTestingModule({ declarations: [FormControlNgModel], imports: [ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'always'})], }); const fixture = TestBed.createComponent(FormControlNgModel); fixture.componentInstance.control = new FormControl(''); fixture.componentInstance.passwordControl = new FormControl(''); fixture.detectChanges(); tick(); expect(warnSpy.calls.count()).toEqual(2); expect(warnSpy.calls.mostRecent().args[0]).toMatch( /It looks like you're using ngModel on the same form field as formControl/gi, ); })); it('should silence warnings when global provider is provided with "never"', fakeAsync(() => { TestBed.configureTestingModule({ declarations: [FormControlNgModel], imports: [ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'})], }); const fixture = TestBed.createComponent(FormControlNgModel); fixture.componentInstance.control = new FormControl(''); fixture.componentInstance.passwordControl = new FormControl(''); fixture.detectChanges(); tick(); expect(warnSpy).not.toHaveBeenCalled(); })); }); it('should support ngModel for complex forms', fakeAsync(() => { const fixture = initTest(FormGroupNgModel); fixture.componentInstance.form = new FormGroup({ 'login': new FormControl(''), 'password': new FormControl(''), }); fixture.componentInstance.login = 'oldValue'; fixture.detectChanges(); tick(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input.value).toEqual('oldValue'); input.value = 'updatedValue'; dispatchEvent(input, 'input'); tick(); expect(fixture.componentInstance.login).toEqual('updatedValue'); })); it('should support ngModel for single fields', fakeAsync(() => { const fixture = initTest(FormControlNgModel); fixture.componentInstance.control = new FormControl(''); fixture.componentInstance.passwordControl = new FormControl(''); fixture.componentInstance.login = 'oldValue'; fixture.detectChanges(); tick(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input.value).toEqual('oldValue'); input.value = 'updatedValue'; dispatchEvent(input, 'input'); tick(); expect(fixture.componentInstance.login).toEqual('updatedValue'); })); it('should not update the view when the value initially came from the view', fakeAsync(() => { if (isNode) return; const fixture = initTest(FormControlNgModel); fixture.componentInstance.control = new FormControl(''); fixture.componentInstance.passwordControl = new FormControl(''); fixture.detectChanges(); tick(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'aa'; input.setSelectionRange(1, 2); dispatchEvent(input, 'input'); fixture.detectChanges(); tick(); // selection start has not changed because we did not reset the value expect(input.selectionStart).toEqual(1); })); it('should work with updateOn submit', fakeAsync(() => { const fixture = initTest(FormGroupNgModel); const formGroup = new FormGroup({ login: new FormControl('', {updateOn: 'submit'}), password: new FormControl(''), }); fixture.componentInstance.form = formGroup; fixture.componentInstance.login = 'initial'; fixture.detectChanges(); tick(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); tick(); expect(fixture.componentInstance.login) .withContext('Expected ngModel value to remain unchanged on input.') .toEqual('initial'); const form = fixture.debugElement.query(By.css('form')).nativeElement; dispatchEvent(form, 'submit'); fixture.detectChanges(); tick(); expect(fixture.componentInstance.login) .withContext('Expected ngModel value to update on submit.') .toEqual('Nancy'); })); });
{ "end_byte": 107753, "start_byte": 101396, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_107757_117370
escribe('validations', () => { it('required validator should validate checkbox', () => { const fixture = initTest(FormControlCheckboxRequiredValidator); const control = new FormControl(false, Validators.requiredTrue); fixture.componentInstance.control = control; fixture.detectChanges(); const checkbox = fixture.debugElement.query(By.css('input')); expect(checkbox.nativeElement.checked).toBe(false); expect(control.hasError('required')).toEqual(true); checkbox.nativeElement.checked = true; dispatchEvent(checkbox.nativeElement, 'change'); fixture.detectChanges(); expect(checkbox.nativeElement.checked).toBe(true); expect(control.hasError('required')).toEqual(false); checkbox.nativeElement.required = false; dispatchEvent(checkbox.nativeElement, 'change'); fixture.detectChanges(); expect(checkbox.nativeElement.checked).toBe(true); expect(control.hasError('required')).toEqual(false); checkbox.nativeElement.checked = false; checkbox.nativeElement.required = true; dispatchEvent(checkbox.nativeElement, 'change'); fixture.detectChanges(); expect(checkbox.nativeElement.checked).toBe(false); expect(control.hasError('required')).toEqual(true); }); // Note: this scenario goes against validator function rules were `null` is the only // representation of a successful check. However the `Validators.combine` has a side-effect // where falsy values are treated as success and `null` is returned from the wrapper function. // The goal of this test is to prevent regressions for validators that return falsy values by // mistake and rely on the `Validators.compose` side-effects to normalize the value to `null` // instead. it('should treat validators that return `undefined` as successful', () => { const fixture = initTest(FormControlComp); const validatorFn = (control: AbstractControl) => control.value ?? undefined; const control = new FormControl(undefined, validatorFn); fixture.componentInstance.control = control; fixture.detectChanges(); expect(control.status).toBe('VALID'); expect(control.errors).toBe(null); }); it('should use sync validators defined in html', () => { const fixture = initTest(LoginIsEmptyWrapper, LoginIsEmptyValidator); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = form; fixture.detectChanges(); const required = fixture.debugElement.query(By.css('[required]')); const minLength = fixture.debugElement.query(By.css('[minlength]')); const maxLength = fixture.debugElement.query(By.css('[maxlength]')); const pattern = fixture.debugElement.query(By.css('[pattern]')); required.nativeElement.value = ''; minLength.nativeElement.value = '1'; maxLength.nativeElement.value = '1234'; pattern.nativeElement.value = '12'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.hasError('required', ['login'])).toEqual(true); expect(form.hasError('minlength', ['min'])).toEqual(true); expect(form.hasError('maxlength', ['max'])).toEqual(true); expect(form.hasError('pattern', ['pattern'])).toEqual(true); expect(form.hasError('loginIsEmpty')).toEqual(true); required.nativeElement.value = '1'; minLength.nativeElement.value = '123'; maxLength.nativeElement.value = '123'; pattern.nativeElement.value = '123'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.valid).toEqual(true); }); it('should use sync validators using bindings', () => { const fixture = initTest(ValidationBindingsForm); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = form; fixture.componentInstance.required = true; fixture.componentInstance.minLen = 3; fixture.componentInstance.maxLen = 3; fixture.componentInstance.pattern = '.{3,}'; fixture.detectChanges(); const required = fixture.debugElement.query(By.css('[name=required]')); const minLength = fixture.debugElement.query(By.css('[name=minlength]')); const maxLength = fixture.debugElement.query(By.css('[name=maxlength]')); const pattern = fixture.debugElement.query(By.css('[name=pattern]')); required.nativeElement.value = ''; minLength.nativeElement.value = '1'; maxLength.nativeElement.value = '1234'; pattern.nativeElement.value = '12'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.hasError('required', ['login'])).toEqual(true); expect(form.hasError('minlength', ['min'])).toEqual(true); expect(form.hasError('maxlength', ['max'])).toEqual(true); expect(form.hasError('pattern', ['pattern'])).toEqual(true); required.nativeElement.value = '1'; minLength.nativeElement.value = '123'; maxLength.nativeElement.value = '123'; pattern.nativeElement.value = '123'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.valid).toEqual(true); }); it('changes on bound properties should change the validation state of the form', () => { const fixture = initTest(ValidationBindingsForm); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = form; fixture.detectChanges(); const required = fixture.debugElement.query(By.css('[name=required]')); const minLength = fixture.debugElement.query(By.css('[name=minlength]')); const maxLength = fixture.debugElement.query(By.css('[name=maxlength]')); const pattern = fixture.debugElement.query(By.css('[name=pattern]')); required.nativeElement.value = ''; minLength.nativeElement.value = '1'; maxLength.nativeElement.value = '1234'; pattern.nativeElement.value = '12'; dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.hasError('required', ['login'])).toEqual(false); expect(form.hasError('minlength', ['min'])).toEqual(false); expect(form.hasError('maxlength', ['max'])).toEqual(false); expect(form.hasError('pattern', ['pattern'])).toEqual(false); expect(form.valid).toEqual(true); fixture.componentInstance.required = true; fixture.componentInstance.minLen = 3; fixture.componentInstance.maxLen = 3; fixture.componentInstance.pattern = '.{3,}'; fixture.detectChanges(); dispatchEvent(required.nativeElement, 'input'); dispatchEvent(minLength.nativeElement, 'input'); dispatchEvent(maxLength.nativeElement, 'input'); dispatchEvent(pattern.nativeElement, 'input'); expect(form.hasError('required', ['login'])).toEqual(true); expect(form.hasError('minlength', ['min'])).toEqual(true); expect(form.hasError('maxlength', ['max'])).toEqual(true); expect(form.hasError('pattern', ['pattern'])).toEqual(true); expect(form.valid).toEqual(false); expect(required.nativeElement.getAttribute('required')).toEqual(''); expect(fixture.componentInstance.minLen.toString()).toEqual( minLength.nativeElement.getAttribute('minlength'), ); expect(fixture.componentInstance.maxLen.toString()).toEqual( maxLength.nativeElement.getAttribute('maxlength'), ); expect(fixture.componentInstance.pattern.toString()).toEqual( pattern.nativeElement.getAttribute('pattern'), ); fixture.componentInstance.required = false; fixture.componentInstance.minLen = null!; fixture.componentInstance.maxLen = null!; fixture.componentInstance.pattern = null!; fixture.detectChanges(); expect(form.hasError('required', ['login'])).toEqual(false); expect(form.hasError('minlength', ['min'])).toEqual(false); expect(form.hasError('maxlength', ['max'])).toEqual(false); expect(form.hasError('pattern', ['pattern'])).toEqual(false); expect(form.valid).toEqual(true); expect(required.nativeElement.getAttribute('required')).toEqual(null); expect(required.nativeElement.getAttribute('minlength')).toEqual(null); expect(required.nativeElement.getAttribute('maxlength')).toEqual(null); expect(required.nativeElement.getAttribute('pattern')).toEqual(null); });
{ "end_byte": 117370, "start_byte": 107757, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_117376_125399
t('should support rebound controls with rebound validators', () => { const fixture = initTest(ValidationBindingsForm); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = form; fixture.componentInstance.required = true; fixture.componentInstance.minLen = 3; fixture.componentInstance.maxLen = 3; fixture.componentInstance.pattern = '.{3,}'; fixture.detectChanges(); const newForm = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = newForm; fixture.detectChanges(); fixture.componentInstance.required = false; fixture.componentInstance.minLen = null!; fixture.componentInstance.maxLen = null!; fixture.componentInstance.pattern = null!; fixture.detectChanges(); expect(newForm.hasError('required', ['login'])).toEqual(false); expect(newForm.hasError('minlength', ['min'])).toEqual(false); expect(newForm.hasError('maxlength', ['max'])).toEqual(false); expect(newForm.hasError('pattern', ['pattern'])).toEqual(false); expect(newForm.valid).toEqual(true); }); it('should use async validators defined in the html', fakeAsync(() => { const fixture = initTest(UniqLoginWrapper, UniqLoginValidator); const form = new FormGroup({'login': new FormControl('')}); tick(); fixture.componentInstance.form = form; fixture.detectChanges(); expect(form.pending).toEqual(true); tick(100); expect(form.hasError('uniqLogin', ['login'])).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'expected'; dispatchEvent(input.nativeElement, 'input'); tick(100); expect(form.valid).toEqual(true); })); it('should use sync validators defined in the model', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('aa', Validators.required)}); fixture.componentInstance.form = form; fixture.detectChanges(); expect(form.valid).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = ''; dispatchEvent(input.nativeElement, 'input'); expect(form.valid).toEqual(false); }); it('should use async validators defined in the model', fakeAsync(() => { const fixture = initTest(FormGroupComp); const control = new FormControl('', Validators.required, uniqLoginAsyncValidator('expected')); const form = new FormGroup({'login': control}); fixture.componentInstance.form = form; fixture.detectChanges(); tick(); expect(form.hasError('required', ['login'])).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'wrong value'; dispatchEvent(input.nativeElement, 'input'); expect(form.pending).toEqual(true); tick(); expect(form.hasError('uniqLogin', ['login'])).toEqual(true); input.nativeElement.value = 'expected'; dispatchEvent(input.nativeElement, 'input'); tick(); expect(form.valid).toEqual(true); })); it('async validator should not override result of sync validator', fakeAsync(() => { const fixture = initTest(FormGroupComp); const control = new FormControl( '', Validators.required, uniqLoginAsyncValidator('expected', 100), ); fixture.componentInstance.form = new FormGroup({'login': control}); fixture.detectChanges(); tick(); expect(control.hasError('required')).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'expected'; dispatchEvent(input.nativeElement, 'input'); expect(control.pending).toEqual(true); input.nativeElement.value = ''; dispatchEvent(input.nativeElement, 'input'); tick(110); expect(control.valid).toEqual(false); })); it('should handle async validation changes in parent and child controls', fakeAsync(() => { const fixture = initTest(FormGroupComp); const control = new FormControl( '', Validators.required, asyncValidator((c) => !!c.value && c.value.length > 3, 100), ); const form = new FormGroup( {'login': control}, null, asyncValidator((c) => c.get('login')!.value.includes('angular'), 200), ); fixture.componentInstance.form = form; fixture.detectChanges(); tick(); // Initially, the form is invalid because the nested mandatory control is empty expect(control.hasError('required')).toEqual(true); expect(form.value).toEqual({'login': ''}); expect(form.invalid).toEqual(true); // Setting a value in the form control that will trigger the registered asynchronous // validation const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'angul'; dispatchEvent(input.nativeElement, 'input'); // The form control asynchronous validation is in progress (for 100 ms) expect(control.pending).toEqual(true); tick(100); // Now the asynchronous validation has resolved, and since the form control value // (`angul`) has a length > 3, the validation is successful expect(control.invalid).toEqual(false); // Even if the child control is valid, the form control is pending because it is still // waiting for its own validation expect(form.pending).toEqual(true); tick(100); // Login form control is valid. However, the form control is invalid because `angul` does // not include `angular` expect(control.invalid).toEqual(false); expect(form.pending).toEqual(false); expect(form.invalid).toEqual(true); // Setting a value that would be trigger "VALID" form state input.nativeElement.value = 'angular!'; dispatchEvent(input.nativeElement, 'input'); // Since the form control value changed, its asynchronous validation runs for 100ms expect(control.pending).toEqual(true); tick(100); // Even if the child control is valid, the form control is pending because it is still // waiting for its own validation expect(control.invalid).toEqual(false); expect(form.pending).toEqual(true); tick(100); // Now, the form is valid because its own asynchronous validation has resolved // successfully, because the form control value `angular` includes the `angular` string expect(control.invalid).toEqual(false); expect(form.pending).toEqual(false); expect(form.invalid).toEqual(false); })); it('should cancel observable properly between validation runs', fakeAsync(() => { const fixture = initTest(FormControlComp); const resultArr: number[] = []; fixture.componentInstance.control = new FormControl( '', null!, observableValidator(resultArr), ); fixture.detectChanges(); tick(100); expect(resultArr.length) .withContext(`Expected source observable to emit once on init.`) .toEqual(1); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'a'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); input.nativeElement.value = 'aa'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); tick(100); expect(resultArr.length) .withContext(`Expected original observable to be canceled on the next value change.`) .toEqual(2); }));
{ "end_byte": 125399, "start_byte": 117376, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_125405_132732
escribe('enabling validators conditionally', () => { it('should not activate minlength and maxlength validators if input is null', () => { @Component({ selector: 'min-max-length-null', template: ` <form [formGroup]="form"> <input [formControl]="control" name="control" [minlength]="minlen" [maxlength]="maxlen"> </form> `, standalone: false, }) class MinMaxLengthComponent { control: FormControl = new FormControl(); form: FormGroup = new FormGroup({'control': this.control}); minlen: number | null = null; maxlen: number | null = null; } const fixture = initTest(MinMaxLengthComponent); const control = fixture.componentInstance.control; fixture.detectChanges(); const form = fixture.componentInstance.form; const input = fixture.debugElement.query(By.css('input')).nativeElement; interface minmax { minlength: number | null; maxlength: number | null; } interface state { isValid: boolean; failedValidator?: string; } const setInputValue = (value: number) => { input.value = value; dispatchEvent(input, 'input'); fixture.detectChanges(); }; const setValidatorValues = (values: minmax) => { fixture.componentInstance.minlen = values.minlength; fixture.componentInstance.maxlen = values.maxlength; fixture.detectChanges(); }; const verifyValidatorAttrValues = (values: {minlength: any; maxlength: any}) => { expect(input.getAttribute('minlength')).toBe(values.minlength); expect(input.getAttribute('maxlength')).toBe(values.maxlength); }; const verifyFormState = (state: state) => { expect(form.valid).toBe(state.isValid); if (state.failedValidator) { expect(control!.hasError('minlength')).toEqual(state.failedValidator === 'minlength'); expect(control!.hasError('maxlength')).toEqual(state.failedValidator === 'maxlength'); } }; ////////// Actual test scenarios start below ////////// // 1. Verify that validators are disabled when input is `null`. setValidatorValues({minlength: null, maxlength: null}); verifyValidatorAttrValues({minlength: null, maxlength: null}); verifyFormState({isValid: true}); // 2. Verify that setting validator inputs (to a value different from `null`) activate // validators. setInputValue(12345); setValidatorValues({minlength: 2, maxlength: 4}); verifyValidatorAttrValues({minlength: '2', maxlength: '4'}); verifyFormState({isValid: false, failedValidator: 'maxlength'}); // 3. Changing value to the valid range should make the form valid. setInputValue(123); verifyFormState({isValid: true}); // 4. Changing value to trigger `minlength` validator. setInputValue(1); verifyFormState({isValid: false, failedValidator: 'minlength'}); // 5. Changing validator inputs to verify that attribute values are updated (and the form // is now valid). setInputValue(1); setValidatorValues({minlength: 1, maxlength: 5}); verifyValidatorAttrValues({minlength: '1', maxlength: '5'}); verifyFormState({isValid: true}); // 6. Reset validator inputs back to `null` should deactivate validators. setInputValue(123); setValidatorValues({minlength: null, maxlength: null}); verifyValidatorAttrValues({minlength: null, maxlength: null}); verifyFormState({isValid: true}); }); it('should not activate min and max validators if input is null', () => { @Component({ selector: 'min-max-null', template: ` <form [formGroup]="form"> <input type="number" [formControl]="control" name="minmaxinput" [min]="minlen" [max]="maxlen"> </form> `, standalone: false, }) class MinMaxComponent { control: FormControl = new FormControl(); form: FormGroup = new FormGroup({'control': this.control}); minlen: number | null = null; maxlen: number | null = null; } const fixture = initTest(MinMaxComponent); const control = fixture.componentInstance.control; fixture.detectChanges(); const form = fixture.componentInstance.form; const input = fixture.debugElement.query(By.css('input')).nativeElement; interface minmax { min: number | null; max: number | null; } interface state { isValid: boolean; failedValidator?: string; } const setInputValue = (value: number) => { input.value = value; dispatchEvent(input, 'input'); fixture.detectChanges(); }; const setValidatorValues = (values: minmax) => { fixture.componentInstance.minlen = values.min; fixture.componentInstance.maxlen = values.max; fixture.detectChanges(); }; const verifyValidatorAttrValues = (values: {min: any; max: any}) => { expect(input.getAttribute('min')).toBe(values.min); expect(input.getAttribute('max')).toBe(values.max); }; const verifyFormState = (state: state) => { expect(form.valid).toBe(state.isValid); if (state.failedValidator) { expect(control!.hasError('min')).toEqual(state.failedValidator === 'min'); expect(control!.hasError('max')).toEqual(state.failedValidator === 'max'); } }; ////////// Actual test scenarios start below ////////// // 1. Verify that validators are disabled when input is `null`. setValidatorValues({min: null, max: null}); verifyValidatorAttrValues({min: null, max: null}); verifyFormState({isValid: true}); // 2. Verify that setting validator inputs (to a value different from `null`) activate // validators. setInputValue(12345); setValidatorValues({min: 2, max: 4}); verifyValidatorAttrValues({min: '2', max: '4'}); verifyFormState({isValid: false, failedValidator: 'max'}); // 3. Changing value to the valid range should make the form valid. setInputValue(3); verifyFormState({isValid: true}); // 4. Changing value to trigger `minlength` validator. setInputValue(1); verifyFormState({isValid: false, failedValidator: 'min'}); // 5. Changing validator inputs to verify that attribute values are updated (and the form // is now valid). setInputValue(1); setValidatorValues({min: 1, max: 5}); verifyValidatorAttrValues({min: '1', max: '5'}); verifyFormState({isValid: true}); // 6. Reset validator inputs back to `null` should deactivate validators. setInputValue(123); setValidatorValues({min: null, max: null}); verifyValidatorAttrValues({min: null, max: null}); verifyFormState({isValid: true}); }); });
{ "end_byte": 132732, "start_byte": 125405, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_132738_142652
cribe('min and max validators', () => { function getComponent(dir: string): Type<MinMaxFormControlComp | MinMaxFormControlNameComp> { return dir === 'formControl' ? MinMaxFormControlComp : MinMaxFormControlNameComp; } // Run tests for both `FormControlName` and `FormControl` directives ['formControl', 'formControlName'].forEach((dir: string) => { it('should validate max', () => { const fixture = initTest(getComponent(dir)); const control = new FormControl(5); fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.value).toEqual('5'); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = 2; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 2}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); fixture.componentInstance.max = 1; fixture.detectChanges(); expect(input.getAttribute('max')).toEqual('1'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({max: {max: 1, actual: 2}}); fixture.componentInstance.min = 0; fixture.componentInstance.max = 0; fixture.detectChanges(); expect(input.getAttribute('min')).toEqual('0'); expect(input.getAttribute('max')).toEqual('0'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({max: {max: 0, actual: 2}}); input.value = 0; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); }); it('should validate max for float number', () => { const fixture = initTest(getComponent(dir)); const control = new FormControl(10.25); fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.componentInstance.max = 10.35; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.getAttribute('max')).toEqual('10.35'); expect(input.value).toEqual('10.25'); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = 10.15; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 10.15}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); fixture.componentInstance.max = 10.05; fixture.detectChanges(); expect(input.getAttribute('max')).toEqual('10.05'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({max: {max: 10.05, actual: 10.15}}); input.value = 10.01; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 10.01}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); }); it('should apply max validation when control value is defined as a string', () => { const fixture = initTest(getComponent(dir)); const control = new FormControl('5'); fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.value).toEqual('5'); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = '2'; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 2}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); fixture.componentInstance.max = 1; fixture.detectChanges(); expect(input.getAttribute('max')).toEqual('1'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({max: {max: 1, actual: 2}}); }); it('should validate min', () => { const fixture = initTest(getComponent(dir)); const control = new FormControl(5); fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.value).toEqual('5'); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = 2; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 2}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); fixture.componentInstance.min = 5; fixture.detectChanges(); expect(input.getAttribute('min')).toEqual('5'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({min: {min: 5, actual: 2}}); fixture.componentInstance.min = 0; input.value = -5; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(input.getAttribute('min')).toEqual('0'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({min: {min: 0, actual: -5}}); input.value = 0; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); }); it('should validate min for float number', () => { const fixture = initTest(getComponent(dir)); const control = new FormControl(10.25); fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.componentInstance.max = 10.5; fixture.componentInstance.min = 10.25; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.getAttribute('min')).toEqual('10.25'); expect(input.getAttribute('max')).toEqual('10.5'); expect(input.value).toEqual('10.25'); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = 10.35; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 10.35}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); fixture.componentInstance.min = 10.4; fixture.detectChanges(); expect(input.getAttribute('min')).toEqual('10.4'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({min: {min: 10.4, actual: 10.35}}); input.value = 10.45; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 10.45}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); }); it('should apply min validation when control value is defined as a string', () => { const fixture = initTest(getComponent(dir)); const control = new FormControl('5'); fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.value).toEqual('5'); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = '2'; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 2}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); fixture.componentInstance.min = 5; fixture.detectChanges(); expect(input.getAttribute('min')).toEqual('5'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({min: {min: 5, actual: 2}}); }); it('should run min/max validation for empty values', () => { const fixture = initTest(getComponent(dir)); const minValidateFnSpy = spyOn(MinValidator.prototype, 'validate'); const maxValidateFnSpy = spyOn(MaxValidator.prototype, 'validate'); const control = new FormControl(); fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.value).toEqual(''); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); expect(minValidateFnSpy).toHaveBeenCalled(); expect(maxValidateFnSpy).toHaveBeenCalled(); });
{ "end_byte": 142652, "start_byte": 132738, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_142662_148190
'should run min/max validation when constraints are represented as strings', () => { const fixture = initTest(getComponent(dir)); const control = new FormControl(5); // Run tests when min and max are defined as strings. fixture.componentInstance.min = '1'; fixture.componentInstance.max = '10'; fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.value).toEqual('5'); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = 2; // inside [1, 10] range dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 2}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = -2; // outside [1, 10] range dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: -2}); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({min: {min: 1, actual: -2}}); input.value = 20; // outside [1, 10] range dispatchEvent(input, 'input'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({max: {max: 10, actual: 20}}); }); it('should run min/max validation for negative values', () => { const fixture = initTest(getComponent(dir)); const control = new FormControl(-30); fixture.componentInstance.control = control; fixture.componentInstance.form = new FormGroup({'pin': control}); fixture.componentInstance.min = -20; fixture.componentInstance.max = -10; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; const form = fixture.componentInstance.form; expect(input.value).toEqual('-30'); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({min: {min: -20, actual: -30}}); input.value = -15; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: -15}); expect(form.valid).toBeTruthy(); expect(form.controls['pin'].errors).toBeNull(); input.value = -5; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: -5}); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({max: {max: -10, actual: -5}}); input.value = 0; dispatchEvent(input, 'input'); expect(form.value).toEqual({pin: 0}); expect(form.valid).toBeFalse(); expect(form.controls['pin'].errors).toEqual({max: {max: -10, actual: 0}}); }); }); it('should fire registerOnValidatorChange for validators attached to the formGroups', () => { let registerOnValidatorChangeFired = 0; let registerOnAsyncValidatorChangeFired = 0; @Directive({ selector: '[ng-noop-validator]', providers: [ {provide: NG_VALIDATORS, useExisting: forwardRef(() => NoOpValidator), multi: true}, ], standalone: false, }) class NoOpValidator implements Validator { @Input() validatorInput = ''; validate(c: AbstractControl) { return null; } public registerOnValidatorChange(fn: () => void) { registerOnValidatorChangeFired++; } } @Directive({ selector: '[ng-noop-async-validator]', providers: [ { provide: NG_ASYNC_VALIDATORS, useExisting: forwardRef(() => NoOpAsyncValidator), multi: true, }, ], standalone: false, }) class NoOpAsyncValidator implements AsyncValidator { @Input() validatorInput = ''; validate(c: AbstractControl) { return Promise.resolve(null); } public registerOnValidatorChange(fn: () => void) { registerOnAsyncValidatorChangeFired++; } } @Component({ selector: 'ng-model-noop-validation', template: ` <form [formGroup]="fooGroup" ng-noop-validator ng-noop-async-validator [validatorInput]="validatorInput"> <input type="text" formControlName="fooInput"> </form> `, standalone: false, }) class NgModelNoOpValidation { validatorInput = 'bar'; fooGroup = new FormGroup({ fooInput: new FormControl(''), }); } const fixture = initTest(NgModelNoOpValidation, NoOpValidator, NoOpAsyncValidator); fixture.detectChanges(); expect(registerOnValidatorChangeFired).toBe(1); expect(registerOnAsyncValidatorChangeFired).toBe(1); fixture.componentInstance.validatorInput = 'baz'; fixture.detectChanges(); // Changing the validator input should not cause the onValidatorChange to be called // again. expect(registerOnValidatorChangeFired).toBe(1); expect(registerOnAsyncValidatorChangeFired).toBe(1); }); }); });
{ "end_byte": 148190, "start_byte": 142662, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_148194_156237
cribe('errors', () => { it("should throw if a form isn't passed into formGroup", () => { const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowError( new RegExp(`formGroup expects a FormGroup instance`), ); }); it('should throw if formControlName is used without a control container', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <input type="text" formControlName="login"> `, }, }); const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowMatching((e: Error) => { if (!e.message.includes(`formControlName must be used with a parent formGroup directive`)) { return false; } if (!e.message.includes(`Affected Form Control name: "login"`)) { return false; } return true; }); }); it('should throw if formControlName, with an index, is used without a control container', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <input type="text" [formControlName]="0"> `, }, }); const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowMatching((e: Error) => { if (!e.message.includes(`formControlName must be used with a parent formGroup directive`)) { return false; } if (!e.message.includes(`Affected Form Control index: "0"`)) { return false; } return true; }); }); it('should throw, without indicating the affected form control, if formControlName is used without a control container', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <input type="text" formControlName> `, }, }); const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowMatching((e: Error) => { if (!e.message.includes(`formControlName must be used with a parent formGroup directive`)) { return false; } if (e.message.includes(`Affected Form Control`)) { return false; } return true; }); }); it('should throw if formControlName is used with NgForm', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <form> <input type="text" formControlName="login"> </form> `, }, }); const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowError( new RegExp(`formControlName must be used with a parent formGroup directive.`), ); }); it('should throw if formControlName is used with NgModelGroup', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <form> <div ngModelGroup="parent"> <input type="text" formControlName="login"> </div> </form> `, }, }); const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowError( new RegExp(`formControlName cannot be used with an ngModelGroup parent.`), ); }); it('should throw if formGroupName is used without a control container', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div formGroupName="person"> <input type="text" formControlName="login"> </div> `, }, }); const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowError( new RegExp(`formGroupName must be used with a parent formGroup directive`), ); }); it('should throw if formGroupName is used with NgForm', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <form> <div formGroupName="person"> <input type="text" formControlName="login"> </div> </form> `, }, }); const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowError( new RegExp(`formGroupName must be used with a parent formGroup directive.`), ); }); it('should throw if formArrayName is used without a control container', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div formArrayName="cities"> <input type="text" formControlName="login"> </div>`, }, }); const fixture = initTest(FormGroupComp); expect(() => fixture.detectChanges()).toThrowError( new RegExp(`formArrayName must be used with a parent formGroup directive`), ); }); it('should throw if ngModel is used alone under formGroup', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div [formGroup]="form"> <input type="text" [(ngModel)]="data"> </div> `, }, }); const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({}); expect(() => fixture.detectChanges()).toThrowError( new RegExp( `ngModel cannot be used to register form controls with a parent formGroup directive.`, ), ); }); it('should not throw if ngModel is used alone under formGroup with standalone: true', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div [formGroup]="form"> <input type="text" [(ngModel)]="data" [ngModelOptions]="{standalone: true}"> </div> `, }, }); const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({}); expect(() => fixture.detectChanges()).not.toThrowError(); }); it('should throw if ngModel is used alone with formGroupName', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div [formGroup]="form"> <div formGroupName="person"> <input type="text" [(ngModel)]="data"> </div> </div> `, }, }); const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({person: new FormGroup({})}); expect(() => fixture.detectChanges()).toThrowError( new RegExp( `ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.`, ), ); }); it('should throw if ngModelGroup is used with formGroup', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <div [formGroup]="form"> <div ngModelGroup="person"> <input type="text" [(ngModel)]="data"> </div> </div> `, }, }); const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({}); expect(() => fixture.detectChanges()).toThrowError( new RegExp(`ngModelGroup cannot be used with a parent formGroup directive`), ); }); it('should throw if radio button name does not match formControlName attr', () => { TestBed.overrideComponent(FormGroupComp, { set: { template: ` <form [formGroup]="form">hav <input type="radio" formControlName="food" name="drink" value="chicken"> </form>`, }, }); const fixture = initTest(FormGroupComp); fixture.componentInstance.form = new FormGroup({'food': new FormControl('fish')}); expect(() => fixture.detectChanges()).toThrowError( new RegExp('If you define both a name and a formControlName'), ); }); });
{ "end_byte": 156237, "start_byte": 148194, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_156241_160949
cribe('radio groups', () => { it('should respect the attr.disabled state as an initial value', () => { const fixture = initTest(RadioForm); const choice = new FormControl('one'); const form = new FormGroup({'choice': choice}); fixture.componentInstance.form = form; fixture.detectChanges(); const oneInput = fixture.debugElement.query(By.css('input')); // The 'one' input is initially disabled in the view with [attr.disabled]. // The model thinks it is enabled. This inconsistent state was retained for backwards // compatibility. (See `RadioControlValueAccessor` for details.) expect(oneInput.attributes['disabled']).toBe('true'); expect(choice.disabled).toBe(false); // Flipping the attribute back and forth does not change the model // as expected. Once the initial `disabled` value is setup, the model // becomes the source of truth. oneInput.nativeElement.setAttribute('disabled', 'false'); fixture.detectChanges(); expect(oneInput.attributes['disabled']).toBe('false'); expect(choice.disabled).toBe(false); oneInput.nativeElement.setAttribute('disabled', 'true'); fixture.detectChanges(); expect(oneInput.attributes['disabled']).toBe('true'); expect(choice.disabled).toBe(false); oneInput.nativeElement.setAttribute('disabled', 'false'); fixture.detectChanges(); expect(oneInput.attributes['disabled']).toBe('false'); expect(choice.disabled).toBe(false); }); }); describe('IME events', () => { it('should determine IME event handling depending on platform by default', () => { const fixture = initTest(FormControlComp); fixture.componentInstance.control = new FormControl('oldValue'); fixture.detectChanges(); const inputEl = fixture.debugElement.query(By.css('input')); const inputNativeEl = inputEl.nativeElement; expect(inputNativeEl.value).toEqual('oldValue'); inputEl.triggerEventHandler('compositionstart'); inputNativeEl.value = 'updatedValue'; dispatchEvent(inputNativeEl, 'input'); const isAndroid = /android (\d+)/.test(getDOM().getUserAgent().toLowerCase()); if (isAndroid) { // On Android, values should update immediately expect(fixture.componentInstance.control.value).toEqual('updatedValue'); } else { // On other platforms, values should wait for compositionend expect(fixture.componentInstance.control.value).toEqual('oldValue'); inputEl.triggerEventHandler('compositionend', {target: {value: 'updatedValue'}}); fixture.detectChanges(); expect(fixture.componentInstance.control.value).toEqual('updatedValue'); } }); it('should hold IME events until compositionend if composition mode', () => { TestBed.overrideComponent(FormControlComp, { set: {providers: [{provide: COMPOSITION_BUFFER_MODE, useValue: true}]}, }); const fixture = initTest(FormControlComp); fixture.componentInstance.control = new FormControl('oldValue'); fixture.detectChanges(); const inputEl = fixture.debugElement.query(By.css('input')); const inputNativeEl = inputEl.nativeElement; expect(inputNativeEl.value).toEqual('oldValue'); inputEl.triggerEventHandler('compositionstart'); inputNativeEl.value = 'updatedValue'; dispatchEvent(inputNativeEl, 'input'); // should not update when compositionstart expect(fixture.componentInstance.control.value).toEqual('oldValue'); inputEl.triggerEventHandler('compositionend', {target: {value: 'updatedValue'}}); fixture.detectChanges(); // should update when compositionend expect(fixture.componentInstance.control.value).toEqual('updatedValue'); }); it('should work normally with composition events if composition mode is off', () => { TestBed.overrideComponent(FormControlComp, { set: {providers: [{provide: COMPOSITION_BUFFER_MODE, useValue: false}]}, }); const fixture = initTest(FormControlComp); fixture.componentInstance.control = new FormControl('oldValue'); fixture.detectChanges(); const inputEl = fixture.debugElement.query(By.css('input')); const inputNativeEl = inputEl.nativeElement; expect(inputNativeEl.value).toEqual('oldValue'); inputEl.triggerEventHandler('compositionstart'); inputNativeEl.value = 'updatedValue'; dispatchEvent(inputNativeEl, 'input'); fixture.detectChanges(); // formControl should update normally expect(fixture.componentInstance.control.value).toEqual('updatedValue'); }); });
{ "end_byte": 160949, "start_byte": 156241, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_160953_170459
cribe('cleanup', () => { // Symbol that indicates to the verification logic that a certain spy was not expected to be // invoked. This symbol is used by the test helpers below. const SHOULD_NOT_BE_CALLED = Symbol('SHOULD_NOT_BE_INVOKED'); function expectValidatorsToBeCalled( syncValidatorSpy: jasmine.Spy, asyncValidatorSpy: jasmine.Spy, expected: {ctx: any; count: number}, ) { [syncValidatorSpy, asyncValidatorSpy].forEach((spy: jasmine.Spy<jasmine.Func>) => { spy.calls.all().forEach((call: jasmine.CallInfo<jasmine.Func>) => { expect(call.args[0]).toBe(expected.ctx); }); expect(spy).toHaveBeenCalledTimes(expected.count); }); } function createValidatorSpy(): jasmine.Spy<jasmine.Func> { return jasmine.createSpy('asyncValidator').and.returnValue(null); } function createAsyncValidatorSpy(): jasmine.Spy<jasmine.Func> { return jasmine.createSpy('asyncValidator').and.returnValue(Promise.resolve(null)); } // Sets up a control with validators and value accessors configured for a test. function addOwnValidatorsAndAttachSpies(control: AbstractControl, fromView: any = {}): void { const validatorSpy = createValidatorSpy(); const asyncValidatorSpy = createAsyncValidatorSpy(); const valueChangesSpy = jasmine.createSpy('controlValueChangesListener'); const debug: any = { validatorSpy, asyncValidatorSpy, valueChangesSpy, }; if (fromView.viewValidators) { const [syncValidatorClass, asyncValidatorClass] = fromView.viewValidators; debug.viewValidatorSpy = validatorSpyOn(syncValidatorClass); debug.viewAsyncValidatorSpy = validatorSpyOn(asyncValidatorClass); } if (fromView.valueAccessor) { debug.valueAccessorSpy = spyOn(fromView.valueAccessor.prototype, 'writeValue'); } (control as any).__debug__ = debug; control.valueChanges.subscribe(valueChangesSpy); control.setValidators(validatorSpy); control.setAsyncValidators(asyncValidatorSpy); } // Resets all spies associated with given controls. function resetSpies(...controls: AbstractControl[]): void { controls.forEach((control: any) => { const debug = control.__debug__; debug.validatorSpy.calls.reset(); debug.asyncValidatorSpy.calls.reset(); debug.valueChangesSpy.calls.reset(); if (debug.viewValidatorSpy) { debug.viewValidatorSpy.calls.reset(); } if (debug.viewAsyncValidatorSpy) { debug.viewAsyncValidatorSpy.calls.reset(); } if (debug.valueAccessorSpy) { debug.valueAccessorSpy.calls.reset(); } }); } // Verifies whether spy calls match expectations. function verifySpyCalls(spy: any, expectedContext: any, expectedCallCount?: number) { if (expectedContext === SHOULD_NOT_BE_CALLED) { expect(spy).not.toHaveBeenCalled(); } else { expect(spy).toHaveBeenCalledWith(expectedContext); if (expectedCallCount !== undefined) { expect(spy.calls.count()).toBe(expectedCallCount); } } } // Verify whether all spies attached to a given control match expectations. function verifySpies(control: AbstractControl, expected: any = {}) { const debug = (control as any).__debug__; const viewValidatorCallCount = expected.viewValidatorCallCount ?? 1; const ownValidatorCallCount = expected.ownValidatorCallCount ?? 1; const valueAccessorCallCount = expected.valueAccessorCallCount ?? 1; verifySpyCalls(debug.validatorSpy, expected.ownValidators, ownValidatorCallCount); verifySpyCalls(debug.asyncValidatorSpy, expected.ownValidators, ownValidatorCallCount); verifySpyCalls(debug.valueChangesSpy, expected.valueChanges); if (debug.viewValidatorSpy) { verifySpyCalls(debug.viewValidatorSpy, expected.viewValidators, viewValidatorCallCount); } if (debug.viewAsyncValidatorSpy) { verifySpyCalls( debug.viewAsyncValidatorSpy, expected.viewValidators, viewValidatorCallCount, ); } if (debug.valueAccessorSpy) { verifySpyCalls(debug.valueAccessorSpy, expected.valueAccessor, valueAccessorCallCount); } } // Init a test with a predefined set of validator and value accessor classes. function initCleanupTest(component: Type<any>) { const fixture = initTest( component, ViewValidatorA, AsyncViewValidatorA, ViewValidatorB, AsyncViewValidatorB, ViewValidatorC, AsyncViewValidatorC, ValueAccessorA, ValueAccessorB, ); fixture.detectChanges(); return fixture; } it('should clean up validators when FormGroup is replaced', () => { const fixture = initTest(FormGroupWithValidators, ViewValidatorA, AsyncViewValidatorA); fixture.detectChanges(); const newForm = new FormGroup({login: new FormControl('NEW')}); const oldForm = fixture.componentInstance.form; // Update `form` input with a new value. fixture.componentInstance.form = newForm; fixture.detectChanges(); const validatorSpy = validatorSpyOn(ViewValidatorA); const asyncValidatorSpy = validatorSpyOn(AsyncViewValidatorA); // Calling `setValue` for the OLD form should NOT trigger validator calls. oldForm.setValue({login: 'SOME-OLD-VALUE'}); expect(validatorSpy).not.toHaveBeenCalled(); expect(asyncValidatorSpy).not.toHaveBeenCalled(); // Calling `setValue` for the NEW (active) form should trigger validator calls. newForm.setValue({login: 'SOME-NEW-VALUE'}); expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: newForm, count: 1}); }); it('should clean up validators when FormControl inside FormGroup is replaced', () => { const fixture = initTest(FormControlWithValidators, ViewValidatorA, AsyncViewValidatorA); fixture.detectChanges(); const newControl = new FormControl('NEW')!; const oldControl = fixture.componentInstance.form.get('login')!; const validatorSpy = validatorSpyOn(ViewValidatorA); const asyncValidatorSpy = validatorSpyOn(AsyncViewValidatorA); // Update `login` form control with a new `FormControl` instance. fixture.componentInstance.form.removeControl('login'); fixture.componentInstance.form.addControl('login', newControl); fixture.detectChanges(); validatorSpy.calls.reset(); asyncValidatorSpy.calls.reset(); // Calling `setValue` for the OLD control should NOT trigger validator calls. oldControl.setValue('SOME-OLD-VALUE'); expect(validatorSpy).not.toHaveBeenCalled(); expect(asyncValidatorSpy).not.toHaveBeenCalled(); // Calling `setValue` for the NEW (active) control should trigger validator calls. newControl.setValue('SOME-NEW-VALUE'); expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: newControl, count: 1}); }); it('should keep control in pending state if async validator never emits', fakeAsync(() => { const fixture = initTest(FormControlWithAsyncValidatorFn); fixture.detectChanges(); const control = fixture.componentInstance.form.get('login')!; expect(control.status).toBe('PENDING'); control.setValue('SOME-NEW-VALUE'); tick(); // Since validator never emits, we expect a control to be retained in a pending state. expect(control.status).toBe('PENDING'); expect(control.errors).toBe(null); })); it('should call validators defined via `set[Async]Validators` after view init', () => { const fixture = initTest(FormControlWithValidators, ViewValidatorA, AsyncViewValidatorA); fixture.detectChanges(); const control = fixture.componentInstance.form.get('login')!; const initialValidatorSpy = validatorSpyOn(ViewValidatorA); const initialAsyncValidatorSpy = validatorSpyOn(AsyncViewValidatorA); initialValidatorSpy.calls.reset(); initialAsyncValidatorSpy.calls.reset(); control.setValue('VALUE-A'); // Expect initial validators (setup during view creation) to be called. expectValidatorsToBeCalled(initialValidatorSpy, initialAsyncValidatorSpy, { ctx: control, count: 1, }); initialValidatorSpy.calls.reset(); initialAsyncValidatorSpy.calls.reset(); // Create new validators and corresponding spies. const newValidatorSpy = jasmine.createSpy('newValidator').and.returnValue(null); const newAsyncValidatorSpy = jasmine.createSpy('newAsyncValidator').and.returnValue(of(null)); // Set new validators to a control that is already used in a view. // Expect that new validators are applied and old validators are removed. control.setValidators(newValidatorSpy); control.setAsyncValidators(newAsyncValidatorSpy); // Update control value to trigger validation. control.setValue('VALUE-B'); // Verify that initial (inactive) validators were not called. expect(initialValidatorSpy).not.toHaveBeenCalled(); expect(initialAsyncValidatorSpy).not.toHaveBeenCalled(); // Verify that newly applied validators were executed. expectValidatorsToBeCalled(newValidatorSpy, newAsyncValidatorSpy, {ctx: control, count: 1}); });
{ "end_byte": 170459, "start_byte": 160953, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_170465_178960
'should cleanup validators on a control used for multiple `formControlName` directives', () => { const fixture = initTest(NgForFormControlWithValidators, ViewValidatorA, AsyncViewValidatorA); fixture.detectChanges(); const newControl = new FormControl('b')!; const oldControl = fixture.componentInstance.form.get('login')!; const validatorSpy = validatorSpyOn(ViewValidatorA); const asyncValidatorSpy = validatorSpyOn(AsyncViewValidatorA); // Case 1: replace `login` form control with a new `FormControl` instance. fixture.componentInstance.form.removeControl('login'); fixture.componentInstance.form.addControl('login', newControl); fixture.detectChanges(); // Check that validators were called with a new control as a context // and each validator function was called for each control (so 3 times each). expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: newControl, count: 3}); validatorSpy.calls.reset(); asyncValidatorSpy.calls.reset(); // Calling `setValue` for the OLD control should NOT trigger validator calls. oldControl.setValue('SOME-OLD-VALUE'); expect(validatorSpy).not.toHaveBeenCalled(); expect(asyncValidatorSpy).not.toHaveBeenCalled(); // Calling `setValue` for the NEW (active) control should trigger validator calls. newControl.setValue('SOME-NEW-VALUE'); // Check that setting a value on a new control triggers validator calls. expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: newControl, count: 3}); // Case 2: update `logins` to render a new list of elements. fixture.componentInstance.logins = ['a', 'b', 'c', 'd', 'e', 'f']; fixture.detectChanges(); validatorSpy.calls.reset(); asyncValidatorSpy.calls.reset(); // Calling `setValue` for the NEW (active) control should trigger validator calls. newControl.setValue('SOME-NEW-VALUE-2'); // Check that setting a value on a new control triggers validator calls for updated set // of controls (one for each element in the `logins` array). expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: newControl, count: 6}); }); it('should cleanup directive-specific callbacks only', () => { const fixture = initTest(MultipleFormControls, ViewValidatorA, AsyncViewValidatorA); fixture.detectChanges(); const sharedControl = fixture.componentInstance.control; const validatorSpy = validatorSpyOn(ViewValidatorA); const asyncValidatorSpy = validatorSpyOn(AsyncViewValidatorA); sharedControl.setValue('b'); fixture.detectChanges(); // Check that validators were called for each `formControlName` directive instance // (2 times total). expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: sharedControl, count: 2}); // Replace formA with a new instance. This will trigger destroy operation for the // `formControlName` directive that is bound to the `control` FormControl instance. const newFormA = new FormGroup({login: new FormControl('new-a')}); fixture.componentInstance.formA = newFormA; fixture.detectChanges(); validatorSpy.calls.reset(); asyncValidatorSpy.calls.reset(); // Update control with a new value. sharedControl.setValue('d'); fixture.detectChanges(); // We should still see an update to the second <input>. expect(fixture.nativeElement.querySelector('#login').value).toBe('d'); expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: sharedControl, count: 1}); }); it('should clean up callbacks when FormControlDirective is destroyed (simple)', () => { // Scenario: // --------- // [formControl] *ngIf const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); @Component({ selector: 'app', template: ` <input *ngIf="visible" type="text" [formControl]="control" cva-a validators-a> `, standalone: false, }) class App { visible = true; control = control; } const fixture = initCleanupTest(App); resetSpies(control); // Case 1: update control value and verify all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { ownValidators: control, viewValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); // Case 2: hide form control and verify no directive-related callbacks // (validators, value accessors) were invoked. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(control); control.setValue('Updated Value'); // Expectation: // - FormControlDirective was destroyed and connection to default value accessor and view // validators should also be destroyed. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated Value', }); // Case 3: make the form control visible again and verify all callbacks are correctly // attached. fixture.componentInstance.visible = true; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(control); control.setValue('Updated Value (v2)'); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Updated Value (v2)', valueChanges: 'Updated Value (v2)', }); }); it('should clean up when FormControlDirective is destroyed (multiple instances)', () => { // Scenario: // --------- // [formControl] *ngIf // [formControl] const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); @Component({ selector: 'app', template: ` <input type="text" [formControl]="control" cva-a validators-a *ngIf="visible"> <input type="text" [formControl]="control" cva-b> `, standalone: false, }) class App { visible = true; control = control; } const fixture = initCleanupTest(App); // Value accessor for the second <input> without *ngIf. const valueAccessorBSpy = spyOn(ValueAccessorB.prototype, 'writeValue'); // Reset all spies. valueAccessorBSpy.calls.reset(); resetSpies(control); // Case 1: update control value and verify all spies were called. control.setValue('Initial value'); fixture.detectChanges(); expect(valueAccessorBSpy).toHaveBeenCalledWith('Initial value'); verifySpies(control, { ownValidators: control, viewValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); // Case 2: hide form control and verify no directive-related callbacks // (validators, value accessors) were invoked. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. valueAccessorBSpy.calls.reset(); resetSpies(control); control.setValue('Updated Value'); // Expectation: // - FormControlDirective was destroyed and connection to a value accessor and view // validators should also be destroyed. // - Since there is a second instance of the FormControlDirective directive present in the // template, we expect to see calls to value accessor B (since it's applied to // that directive instance) and validators applied on a control instance itself (not a // part of a view setup). expect(valueAccessorBSpy).toHaveBeenCalledWith('Updated Value'); verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated Value', }); });
{ "end_byte": 178960, "start_byte": 170465, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_178966_187486
'should clean up callbacks when FormControlName directive is destroyed', () => { // Scenario: // --------- // [formGroup] // formControlName *ngIf // formControlName const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); @Component({ selector: 'app', template: ` <div [formGroup]="group"> <input type="text" formControlName="control" cva-a validators-a *ngIf="visible"> <input type="text" formControlName="control" cva-b> </div> `, standalone: false, }) class App { visible = true; group = new FormGroup({control}); } const fixture = initCleanupTest(App); // DefaultValueAccessor will be used for the second <input> where no custom CVA is defined. const valueAccessorBSpy = spyOn(ValueAccessorB.prototype, 'writeValue'); // Reset all spies. valueAccessorBSpy.calls.reset(); resetSpies(control); // Case 1: update control value and verify all spies were called. control.setValue('Initial value'); fixture.detectChanges(); expect(valueAccessorBSpy).toHaveBeenCalledWith('Initial value'); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); // Case 2: hide form control and verify no directive-related callbacks // (validators, value accessors) were invoked. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. valueAccessorBSpy.calls.reset(); resetSpies(control); control.setValue('Updated value'); // Expectation: // - `FormControlName` was destroyed and connection to the value accessor A and // validators should also be destroyed. // - Since there is a second instance of `FormControlName` directive present in the // template, we expect to see calls to the value accessor B (since it's applied to // that directive instance) and validators applied on a control instance itself (not a // part of a view setup). expect(valueAccessorBSpy).toHaveBeenCalledWith('Updated value'); verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value', }); }); it('should clean up callbacks when FormGroupDirective is destroyed', () => { // Scenario: // --------- // [formGroup] *ngIf // [formControl] const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const group = new FormGroup({control}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); @Component({ selector: 'app', template: ` <ng-container *ngIf="visible"> <div [formGroup]="group" validators-b> <input type="text" [formControl]="control" cva-a validators-a> </div> </ng-container> `, standalone: false, }) class App { visible = true; control = control; group = group; } const fixture = initCleanupTest(App); resetSpies(group, control); // Case 1: update control value and verify that all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {control: 'Initial value'}, }); // Case 2: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, control); control.setValue('Updated value'); // Expectation: // - `FormGroupDirective` and `FormControlDirective` were destroyed, so connection to value // accessor and view validators should also be destroyed. // - Own validators directly attached to FormGroup and FormControl should still be invoked. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value', }); verifySpies(group, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: group, valueChanges: {control: 'Updated value'}, }); // Case 3: make the form control visible again and verify all callbacks are correctly // attached and invoked. fixture.componentInstance.visible = true; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, control); control.setValue('Updated value (v2)'); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Updated value (v2)', valueChanges: 'Updated value (v2)', }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {control: 'Updated value (v2)'}, }); }); it('should clean up when FormControl is destroyed (but parent FormGroup exists)', () => { // Scenario: // --------- // [formGroup] // [formControl] *ngIf const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const group = new FormGroup({control}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); @Component({ selector: 'app', template: ` <div [formGroup]="group" validators-b> <input *ngIf="visible" type="text" [formControl]="control" cva-a validators-a> </div> `, standalone: false, }) class App { visible = true; control = control; group = group; } const fixture = initCleanupTest(App); resetSpies(group, control); // Case 1: update control value and verify that all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {control: 'Initial value'}, }); // Case 2: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, control); group.setValue({control: 'Updated value'}); // Expectation: // - `FormControlDirective` was destroyed, so connection to value accessor and view // validators should also be destroyed. // - Own validators directly attached to FormGroup and FormControl should still be invoked. // - `FormGroupDirective` was *not* destroyed, so all view validators should be invoked. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value', }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {control: 'Updated value'}, }); });
{ "end_byte": 187486, "start_byte": 178966, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_187492_194047
'should clean up controls produced by *ngFor', () => { // Scenario: // --------- // [formGroup] // [formControl] *ngFor const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const group = new FormGroup({control}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); @Component({ selector: 'app', template: ` <div [formGroup]="group" validators-b *ngIf="visible"> <ng-container *ngFor="let login of logins"> <input type="radio" [value]="login" [formControl]="control" cva-a validators-a> </ng-container> </div> `, standalone: false, }) class App { visible = true; control = control; group = group; logins = ['a', 'b', 'c']; } const fixture = initCleanupTest(App); resetSpies(group, control); // Case 1: update control value and verify that all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { viewValidatorCallCount: 3, // since *ngFor produces 3 [formControl]s valueAccessorCallCount: 3, // since *ngFor produces 3 [formControl]s ownValidatorCallCount: 1, viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {control: 'Initial value'}, }); // Case 2: update the list of logins which would result in cleanups for no longer needed // (thus destroyed) directives. fixture.componentInstance.logins = ['c', 'd']; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, control); control.setValue('Updated value'); verifySpies(control, { viewValidatorCallCount: 2, // since now we have 2 items produced by *ngFor valueAccessorCallCount: 2, // since now we have 2 items produced by *ngFor ownValidatorCallCount: 1, viewValidators: control, ownValidators: control, valueAccessor: 'Updated value', valueChanges: 'Updated value', }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {control: 'Updated value'}, }); // Case 3: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, control); control.setValue('Updated value (v2)'); verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value (v2)', }); verifySpies(group, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: group, valueChanges: {control: 'Updated value (v2)'}, }); }); it('should clean up when FormArrayName is destroyed (but parent FormGroup exists)', () => { // Scenario: // --------- // [formGroup] // formArrayName // formControlName *ngIf const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const arr = new FormArray([control]); addOwnValidatorsAndAttachSpies(arr, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); const group = new FormGroup({arr}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorC, AsyncViewValidatorC], }); @Component({ selector: 'app', template: ` <div [formGroup]="group" validators-c> <ng-container formArrayName="arr" validators-b> <input *ngIf="visible" type="text" formControlName="0" cva-a validators-a> </ng-container> </div> `, standalone: false, }) class App { visible = true; group = group; } const fixture = initCleanupTest(App); resetSpies(group, arr, control); // Case 1: update control value and verify that all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); verifySpies(arr, { viewValidators: arr, ownValidators: arr, valueChanges: ['Initial value'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Initial value']}, }); // Case 2: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, arr, control); control.setValue('Updated value'); // Expectation: // - `FormControlDirective` was destroyed, so connection to value accessor and view // validators should also be destroyed. // - Own validators directly attached to FormGroup, FormArray and FormControl should still // be invoked. // - `FormArrayName` was *not* destroyed, so all view validators should be invoked. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value', }); verifySpies(arr, { viewValidators: arr, ownValidators: arr, valueChanges: ['Updated value'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Updated value']}, }); });
{ "end_byte": 194047, "start_byte": 187492, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_194053_201727
'should clean up when FormArrayName is destroyed (but parent FormGroup exists)', () => { // Scenario: // --------- // [formGroup] // formArrayName *ngIf // formControlName const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const arr = new FormArray([control]); addOwnValidatorsAndAttachSpies(arr, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); const group = new FormGroup({arr}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorC, AsyncViewValidatorC], }); @Component({ selector: 'app', template: ` <div [formGroup]="group" validators-c> <ng-container *ngIf="visible" formArrayName="arr" validators-b> <input type="text" formControlName="0" cva-a validators-a> </ng-container> </div> `, standalone: false, }) class App { visible = true; group = group; } const fixture = initCleanupTest(App); resetSpies(group, arr, control); // Case 1: update control value and verify that all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); verifySpies(arr, { viewValidators: arr, ownValidators: arr, valueChanges: ['Initial value'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Initial value']}, }); // Case 2: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, arr, control); control.setValue('Updated value'); // Expectation: // - `FormArrayName` was destroyed, so connection to view validators should be destroyed. // - Own validators directly attached to FormGroup, FormArray and FormControl should still // be invoked. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value', }); verifySpies(arr, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: arr, valueChanges: ['Updated value'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Updated value']}, }); // Case 3: make the form array control available again and verify all callbacks are // correctly attached and invoked. fixture.componentInstance.visible = true; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, arr, control); control.setValue('Updated value (v2)'); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Updated value (v2)', valueChanges: 'Updated value (v2)', }); verifySpies(arr, { viewValidators: arr, ownValidators: arr, valueChanges: ['Updated value (v2)'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Updated value (v2)']}, }); }); it('should clean up all child controls when FormGroup is destroyed', () => { // Scenario: // --------- // [formGroup] *ngIf // formArrayName // formControlName const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const arr = new FormArray([control]); addOwnValidatorsAndAttachSpies(arr, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); const group = new FormGroup({arr}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorC, AsyncViewValidatorC], }); @Component({ selector: 'app', template: ` <div [formGroup]="group" validators-c *ngIf="visible"> <ng-container formArrayName="arr" validators-b> <input type="text" formControlName="0" cva-a validators-a> </ng-container> </div> `, standalone: false, }) class App { visible = true; group = group; } const fixture = initCleanupTest(App); resetSpies(group, arr, control); // Case 1: update control value and verify that all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); verifySpies(arr, { viewValidators: arr, ownValidators: arr, valueChanges: ['Initial value'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Initial value']}, }); // Case 2: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, arr, control); control.setValue('Updated value'); // Expectation: // - `FormArrayName` was destroyed, so connection to view validators should be destroyed. // - Own validators directly attached to FormGroup, FormArray and FormControl should still // be invoked. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value', }); verifySpies(arr, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: arr, valueChanges: ['Updated value'], }); verifySpies(group, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: group, valueChanges: {arr: ['Updated value']}, }); // Case 3: make the form group available again and verify all callbacks are correctly // attached and invoked. fixture.componentInstance.visible = true; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, arr, control); control.setValue('Updated value (v2)'); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Updated value (v2)', valueChanges: 'Updated value (v2)', }); verifySpies(arr, { viewValidators: arr, ownValidators: arr, valueChanges: ['Updated value (v2)'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Updated value (v2)']}, }); });
{ "end_byte": 201727, "start_byte": 194053, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_201733_209897
'should clean up all child controls (with *ngFor) when FormArrayName is destroyed', () => { // Scenario: // --------- // [formGroup] // formArrayName *ngIf // formControlName *ngFor const controlA = new FormControl('A'); addOwnValidatorsAndAttachSpies(controlA, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const controlB = new FormControl('B'); // Note: since ControlA and ControlB share the same set of validators and value accessor, we // add spies just ones while configuring ControlA (it's not possible to add spies multiple // times). addOwnValidatorsAndAttachSpies(controlB, {}); const arr = new FormArray([controlA, controlB]); addOwnValidatorsAndAttachSpies(arr, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); const group = new FormGroup({arr}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorC, AsyncViewValidatorC], }); @Component({ selector: 'app', template: ` <div [formGroup]="group" validators-c> <ng-container formArrayName="arr" validators-b *ngIf="visible"> <ng-container *ngFor="let i of ids"> <input type="text" [formControlName]="i" cva-a validators-a> </ng-container> </ng-container> </div> `, standalone: false, }) class App { visible = true; group = group; ids = [0, 1]; } const fixture = initCleanupTest(App); resetSpies(group, arr, controlA, controlB); // Case 1: update control value and verify that all spies were called. controlA.setValue('Updated A'); fixture.detectChanges(); verifySpies(controlA, { viewValidators: controlA, ownValidators: controlA, valueAccessor: 'Updated A', valueChanges: 'Updated A', }); verifySpies(controlB, { // ControlB is a sibling to ControlA, so updating ControlA has no effect on ControlB. viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: SHOULD_NOT_BE_CALLED, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: SHOULD_NOT_BE_CALLED, }); verifySpies(arr, { viewValidators: arr, ownValidators: arr, valueChanges: ['Updated A', 'B'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Updated A', 'B']}, }); // Case 2: remove ControlA from the view by updating the list of ids. // Verify that ControlA is detached from the view, but ControlB still works. fixture.componentInstance.ids = [1]; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, arr, controlA, controlB); controlA.setValue('Updated A (v2)'); verifySpies(controlA, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: controlA, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated A (v2)', }); verifySpies(controlB, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: SHOULD_NOT_BE_CALLED, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: SHOULD_NOT_BE_CALLED, }); verifySpies(arr, { viewValidators: arr, ownValidators: arr, valueChanges: ['Updated A (v2)', 'B'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Updated A (v2)', 'B']}, }); // Case 3: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(group, arr, controlA, controlB); controlB.setValue('Updated B'); // Expectation: // - `FormArrayName` was destroyed, so connection to view validators should be destroyed. // - Own validators directly attached to FormGroup, FormArray and FormControl should still // be invoked. verifySpies(controlA, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: SHOULD_NOT_BE_CALLED, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: SHOULD_NOT_BE_CALLED, }); verifySpies(controlB, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: controlB, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated B', }); verifySpies(arr, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: arr, valueChanges: ['Updated A (v2)', 'Updated B'], }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {arr: ['Updated A (v2)', 'Updated B']}, }); }); it('should clean up all child controls when FormGroupName is destroyed', () => { // Scenario: // --------- // [formGroup] // formGroupName *ngIf // formControlName const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const group = new FormGroup({control}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); const root = new FormGroup({group}); addOwnValidatorsAndAttachSpies(root, { viewValidators: [ViewValidatorC, AsyncViewValidatorC], }); @Component({ selector: 'app', template: ` <div [formGroup]="root" validators-c> <ng-container formGroupName="group" validators-b *ngIf="visible"> <input type="text" formControlName="control" cva-a validators-a> </ng-container> </div> `, standalone: false, }) class App { visible = true; root = root; } const fixture = initCleanupTest(App); resetSpies(root, group, control); // Case 1: update control value and verify that all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {control: 'Initial value'}, }); verifySpies(root, { viewValidators: root, ownValidators: root, valueChanges: {group: {control: 'Initial value'}}, }); // Case 2: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(root, group, control); control.setValue('Updated value'); // Expectation: // - `FormGroupName` was destroyed, so connection to view validators should be destroyed. // - Own validators directly attached to FormGroups and FormControl should still // be invoked. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value', }); verifySpies(group, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: group, valueChanges: {control: 'Updated value'}, }); verifySpies(root, { viewValidators: root, ownValidators: root, valueChanges: {group: {control: 'Updated value'}}, }); });
{ "end_byte": 209897, "start_byte": 201733, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_209903_218181
'should clean up all child controls when FormGroup is destroyed', () => { // Scenario: // --------- // [formGroup] *ngIf // formGroupName // formControlName const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); const group = new FormGroup({control}); addOwnValidatorsAndAttachSpies(group, { viewValidators: [ViewValidatorB, AsyncViewValidatorB], }); const root = new FormGroup({group}); addOwnValidatorsAndAttachSpies(root, { viewValidators: [ViewValidatorC, AsyncViewValidatorC], }); @Component({ selector: 'app', template: ` <div [formGroup]="root" validators-c *ngIf="visible"> <ng-container formGroupName="group" validators-b> <input type="text" formControlName="control" cva-a validators-a> </ng-container> </div> `, standalone: false, }) class App { visible = true; root = root; } const fixture = initCleanupTest(App); resetSpies(root, group, control); // Case 1: update control value and verify that all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); verifySpies(group, { viewValidators: group, ownValidators: group, valueChanges: {control: 'Initial value'}, }); verifySpies(root, { viewValidators: root, ownValidators: root, valueChanges: {group: {control: 'Initial value'}}, }); // Case 2: hide form group and verify that no directive-related callbacks // (validators, value accessors) are invoked when we set control value later. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(root, group, control); control.setValue('Updated value'); // Expectation: // - `FormGroup` was destroyed, so connection to view validators should be destroyed. // - Own validators directly attached to FormGroups and FormControl should still // be invoked. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated value', }); verifySpies(group, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: group, valueChanges: {control: 'Updated value'}, }); verifySpies(root, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: root, valueChanges: {group: {control: 'Updated value'}}, }); }); // See https://github.com/angular/angular/issues/40521. it('should properly clean up when FormControlName has no CVA', () => { @Component({ selector: 'no-cva-compo', template: ` <form [formGroup]="form"> <div formControlName="control"></div> </form> `, standalone: false, }) class NoCVAComponent { form = new FormGroup({control: new FormControl()}); } const fixture = initTest(NoCVAComponent); expect(() => { fixture.detectChanges(); }).toThrowError( `NG01203: No value accessor for form control name: 'control'. Find more at https://angular.dev/errors/NG01203`, ); // Making sure that cleanup between tests doesn't cause any issues // for not fully initialized controls. expect(() => { fixture.destroy(); }).not.toThrow(); }); }); }); /** * Creates an async validator using a checker function, a timeout and the error to emit in case of * validation failure * * @param checker A function to decide whether the validator will resolve with success or failure * @param timeout When the validation will resolve * @param error The error message to be emitted in case of validation failure * * @returns An async validator created using a checker function, a timeout and the error to emit in * case of validation failure */ function asyncValidator( checker: (c: AbstractControl) => boolean, timeout: number = 0, error: any = { 'async': true, }, ) { return (c: AbstractControl) => { let resolve: (result: any) => void; const promise = new Promise<any>((res) => { resolve = res; }); const res = checker(c) ? null : error; setTimeout(() => resolve(res), timeout); return promise; }; } function uniqLoginAsyncValidator(expectedValue: string, timeout: number = 0) { return asyncValidator((c) => c.value === expectedValue, timeout, {'uniqLogin': true}); } function observableValidator(resultArr: number[]): AsyncValidatorFn { return (c: AbstractControl) => { return timer(100).pipe(tap((resp: any) => resultArr.push(resp))); }; } function loginIsEmptyGroupValidator(c: FormGroup) { return c.controls['login'].value == '' ? {'loginIsEmpty': true} : null; } @Directive({ selector: '[login-is-empty-validator]', providers: [{provide: NG_VALIDATORS, useValue: loginIsEmptyGroupValidator, multi: true}], standalone: false, }) class LoginIsEmptyValidator {} @Directive({ selector: '[uniq-login-validator]', providers: [ {provide: NG_ASYNC_VALIDATORS, useExisting: forwardRef(() => UniqLoginValidator), multi: true}, ], standalone: false, }) class UniqLoginValidator implements AsyncValidator { @Input('uniq-login-validator') expected: any; validate(c: AbstractControl) { return uniqLoginAsyncValidator(this.expected)(c); } } @Component({ selector: 'form-control-comp', template: `<input type="text" [formControl]="control">`, standalone: false, }) class FormControlComp { control!: FormControl; } @Component({ selector: 'form-group-comp', template: ` <form [formGroup]="form" (ngSubmit)="event=$event"> <input type="text" formControlName="login"> </form>`, standalone: false, }) class FormGroupComp { control!: FormControl; form!: FormGroup; event!: Event; } @Component({ selector: 'nested-form-group-name-comp', template: ` <form [formGroup]="form"> <div formGroupName="signin" login-is-empty-validator> <input formControlName="login"> <input formControlName="password"> </div> <input *ngIf="form.contains('email')" formControlName="email"> </form>`, standalone: false, }) class NestedFormGroupNameComp { form!: FormGroup; } @Component({ selector: 'form-array-comp', template: ` <form [formGroup]="form"> <div formArrayName="cities"> <div *ngFor="let city of cityArray.controls; let i=index"> <input [formControlName]="i"> </div> </div> </form>`, standalone: false, }) class FormArrayComp { form!: FormGroup; cityArray!: FormArray; } @Component({ selector: 'nested-form-array-name-comp', template: ` <form [formGroup]="form"> <div formArrayName="arr"> <input formControlName="0"> </div> </form> `, standalone: false, }) class NestedFormArrayNameComp { form!: FormGroup; } @Component({ selector: 'form-array-nested-group', template: ` <div [formGroup]="form"> <div formArrayName="cities"> <div *ngFor="let city of cityArray.controls; let i=index" [formGroupName]="i"> <input formControlName="town"> <input formControlName="state"> </div> </div> </div>`, standalone: false, }) class FormArrayNestedGroup { form!: FormGroup; cityArray!: FormArray; } @Component({ selector: 'form-group-ng-model', template: ` <form [formGroup]="form"> <input type="text" formControlName="login" [(ngModel)]="login"> <input type="text" formControlName="password" [(ngModel)]="password"> </form>`, standalone: false, }) class FormGroupNgModel { form!: FormGroup; login!: string; password!: string; } @
{ "end_byte": 218181, "start_byte": 209903, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/reactive_integration_spec.ts_218183_223451
mponent({ selector: 'form-control-ng-model', template: ` <input type="text" [formControl]="control" [(ngModel)]="login"> <input type="text" [formControl]="passwordControl" [(ngModel)]="password"> `, standalone: false, }) class FormControlNgModel { control!: FormControl; login!: string; passwordControl!: FormControl; password!: string; } @Component({ selector: 'login-is-empty-wrapper', template: ` <div [formGroup]="form" login-is-empty-validator> <input type="text" formControlName="login" required> <input type="text" formControlName="min" minlength="3"> <input type="text" formControlName="max" maxlength="3"> <input type="text" formControlName="pattern" pattern=".{3,}"> </div>`, standalone: false, }) class LoginIsEmptyWrapper { form!: FormGroup; } @Component({ selector: 'validation-bindings-form', template: ` <div [formGroup]="form"> <input name="required" type="text" formControlName="login" [required]="required"> <input name="minlength" type="text" formControlName="min" [minlength]="minLen"> <input name="maxlength" type="text" formControlName="max" [maxlength]="maxLen"> <input name="pattern" type="text" formControlName="pattern" [pattern]="pattern"> </div>`, standalone: false, }) class ValidationBindingsForm { form!: FormGroup; required!: boolean; minLen!: number; maxLen!: number; pattern!: string; } @Component({ selector: 'form-control-checkbox-validator', template: `<input type="checkbox" [formControl]="control">`, standalone: false, }) class FormControlCheckboxRequiredValidator { control!: FormControl; } @Component({ selector: 'uniq-login-wrapper', template: ` <div [formGroup]="form"> <input type="text" formControlName="login" uniq-login-validator="expected"> </div>`, standalone: false, }) class UniqLoginWrapper { form!: FormGroup; } @Component({ selector: 'form-group-with-validators', template: ` <div [formGroup]="form" validators-a> <input type="text" formControlName="login"> </div> `, standalone: false, }) class FormGroupWithValidators { form = new FormGroup({login: new FormControl('INITIAL')}); } @Component({ selector: 'form-control-with-validators', template: ` <div [formGroup]="form"> <input type="text" formControlName="login"> </div> `, standalone: false, }) class FormControlWithAsyncValidatorFn { control = new FormControl('INITIAL'); form = new FormGroup({login: this.control}); constructor() { this.control.setAsyncValidators(() => { return NEVER.pipe(map((_: any) => ({timeoutError: true}))); }); } } @Component({ selector: 'form-control-with-validators', template: ` <div [formGroup]="form"> <input type="text" formControlName="login" validators-a> </div> `, standalone: false, }) class FormControlWithValidators { form: FormGroup = new FormGroup({login: new FormControl('INITIAL')}); } @Component({ selector: 'ngfor-form-controls-with-validators', template: ` <div [formGroup]="formA"> <input type="radio" formControlName="login" validators-a> </div> <div [formGroup]="formB"> <input type="text" formControlName="login" validators-a id="login"> </div> `, standalone: false, }) class MultipleFormControls { control = new FormControl('a'); formA = new FormGroup({login: this.control}); formB = new FormGroup({login: this.control}); } @Component({ selector: 'ngfor-form-controls-with-validators', template: ` <div [formGroup]="form"> <ng-container *ngFor="let login of logins"> <input type="radio" formControlName="login" [value]="login" validators-a> </ng-container> </div> `, standalone: false, }) class NgForFormControlWithValidators { form: FormGroup = new FormGroup({login: new FormControl('a')}); logins = ['a', 'b', 'c']; } @Component({ selector: 'min-max-form-control-name', template: ` <div [formGroup]="form"> <input type="number" formControlName="pin" [max]="max" [min]="min"> </div>`, standalone: false, }) class MinMaxFormControlNameComp { control!: FormControl; form!: FormGroup; min: number | string = 1; max: number | string = 10; } @Component({ selector: 'min-max-form-control', template: ` <div [formGroup]="form"> <input type="number" [formControl]="control" [max]="max" [min]="min"> </div>`, standalone: false, }) class MinMaxFormControlComp { control!: FormControl; form!: FormGroup; min: number | string = 1; max: number | string = 10; } @Component({ template: ` <dialog open> <form #form method="dialog" [formGroup]="formGroup"> <button>Submit</button> </form> </dialog> `, standalone: false, }) class NativeDialogForm { @ViewChild('form') form!: ElementRef<HTMLFormElement>; formGroup = new FormGroup({}); } @Component({ selector: 'radio-form', template: ` <form [formGroup]="form"> <input type="radio" formControlName="choice" value="one" [attr.disabled]="true"> One <input type="radio" formControlName="choice" value="two"> Two </form> `, standalone: false, }) export class RadioForm { form = new FormGroup({ choice: new FormControl('one'), }); }
{ "end_byte": 223451, "start_byte": 218183, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/reactive_integration_spec.ts" }
angular/packages/forms/test/form_array_spec.ts_0_7618
/** * @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 {fakeAsync, tick} from '@angular/core/testing'; import { AbstractControl, FormArray, FormControl, FormGroup, ValidationErrors, ValidatorFn, } from '@angular/forms'; import {Validators} from '@angular/forms/src/validators'; import {of} from 'rxjs'; import {asyncValidator} from './util'; (function () { describe('FormArray', () => { describe('adding/removing', () => { let a: FormArray; let c1: FormControl, c2: FormControl, c3: FormControl; let logger: string[]; beforeEach(() => { a = new FormArray<any>([]); c1 = new FormControl(1); c2 = new FormControl(2); c3 = new FormControl(3); logger = []; }); it('should support pushing', () => { a.push(c1); expect(a.length).toEqual(1); expect(a.controls).toEqual([c1]); }); it('should support removing', () => { a.push(c1); a.push(c2); a.push(c3); a.removeAt(1); expect(a.controls).toEqual([c1, c3]); }); it('should support clearing', () => { a.push(c1); a.push(c2); a.push(c3); a.clear(); expect(a.controls).toEqual([]); a.clear(); expect(a.controls).toEqual([]); }); it('should support inserting', () => { a.push(c1); a.push(c3); a.insert(1, c2); expect(a.controls).toEqual([c1, c2, c3]); }); it('should not emit events when calling `FormArray.push` with `emitEvent: false`', () => { a.valueChanges.subscribe(() => logger.push('value change')); a.statusChanges.subscribe(() => logger.push('status change')); a.push(c1, {emitEvent: false}); expect(a.length).toEqual(1); expect(a.controls).toEqual([c1]); expect(logger).toEqual([]); }); it('should not emit events when calling `FormArray.removeAt` with `emitEvent: false`', () => { a.push(c1); a.push(c2); a.push(c3); a.valueChanges.subscribe(() => logger.push('value change')); a.statusChanges.subscribe(() => logger.push('status change')); a.removeAt(1, {emitEvent: false}); expect(a.controls).toEqual([c1, c3]); expect(logger).toEqual([]); }); it('should not emit events when calling `FormArray.clear` with `emitEvent: false`', () => { a.push(c1); a.push(c2); a.push(c3); a.valueChanges.subscribe(() => logger.push('value change')); a.statusChanges.subscribe(() => logger.push('status change')); a.clear({emitEvent: false}); expect(a.controls).toEqual([]); expect(logger).toEqual([]); }); it('should not emit events when calling `FormArray.insert` with `emitEvent: false`', () => { a.push(c1); a.push(c3); a.valueChanges.subscribe(() => logger.push('value change')); a.statusChanges.subscribe(() => logger.push('status change')); a.insert(1, c2, {emitEvent: false}); expect(a.controls).toEqual([c1, c2, c3]); expect(logger).toEqual([]); }); it('should not emit events when calling `FormArray.setControl` with `emitEvent: false`', () => { a.push(c1); a.push(c3); a.valueChanges.subscribe(() => logger.push('value change')); a.statusChanges.subscribe(() => logger.push('status change')); a.setControl(1, c2, {emitEvent: false}); expect(a.controls).toEqual([c1, c2]); expect(logger).toEqual([]); }); it('should not emit status change events when `FormArray.push` is called with `emitEvent: false`', () => { // Adding validators to make sure there are no status change event submitted when form // becomes invalid. const validatorFn = (value: any) => (value.controls.length > 0 ? {controls: true} : null); const asyncValidatorFn = (value: any) => of(validatorFn(value)); const arr: FormArray = new FormArray<any>([], validatorFn, asyncValidatorFn); expect(arr.valid).toBe(true); arr.statusChanges.subscribe(() => logger.push('status change')); arr.push(c1, {emitEvent: false}); expect(arr.valid).toBe(false); expect(logger).toEqual([]); }); it('should not emit events on the parent when called with `emitEvent: false`', () => { const form = new FormGroup({child: a}); form.valueChanges.subscribe(() => logger.push('form value change')); a.valueChanges.subscribe(() => logger.push('array value change')); form.statusChanges.subscribe(() => logger.push('form status change')); a.statusChanges.subscribe(() => logger.push('array status change')); a.push(new FormControl(5), {emitEvent: false}); expect(logger).toEqual([]); }); }); describe('value', () => { it('should be the reduced value of the child controls', () => { const a = new FormArray([new FormControl(1), new FormControl(2)]); expect(a.value).toEqual([1, 2]); }); it('should be an empty array when there are no child controls', () => { const a = new FormArray([]); expect(a.value).toEqual([]); }); }); describe('getRawValue()', () => { let a: FormArray; it('should work with nested form groups/arrays', () => { a = new FormArray([ new FormGroup({ 'c2': new FormControl('v2') as AbstractControl, 'c3': new FormControl('v3'), }) as any, new FormArray([new FormControl('v4'), new FormControl('v5')]), ]); a.at(0).get('c3')!.disable(); (a.at(1) as FormArray).at(1).disable(); expect(a.getRawValue()).toEqual([{'c2': 'v2', 'c3': 'v3'}, ['v4', 'v5']]); }); }); describe('markAllAsTouched', () => { it('should mark all descendants as touched', () => { const formArray: FormArray = new FormArray([ new FormControl('v1') as AbstractControl, new FormControl('v2'), new FormGroup({'c1': new FormControl('v1')}), new FormArray([new FormGroup({'c2': new FormControl('v2')})]), ]); expect(formArray.touched).toBe(false); const control1 = formArray.at(0) as FormControl; expect(control1.touched).toBe(false); const group1 = formArray.at(2) as FormGroup; expect(group1.touched).toBe(false); const group1Control1 = group1.get('c1') as FormControl; expect(group1Control1.touched).toBe(false); const innerFormArray = formArray.at(3) as FormArray; expect(innerFormArray.touched).toBe(false); const innerFormArrayGroup = innerFormArray.at(0) as FormGroup; expect(innerFormArrayGroup.touched).toBe(false); const innerFormArrayGroupControl1 = innerFormArrayGroup.get('c2') as FormControl; expect(innerFormArrayGroupControl1.touched).toBe(false); formArray.markAllAsTouched(); expect(formArray.touched).toBe(true); expect(control1.touched).toBe(true); expect(group1.touched).toBe(true); expect(group1Control1.touched).toBe(true); expect(innerFormArray.touched).toBe(true); expect(innerFormArrayGroup.touched).toBe(true); expect(innerFormArrayGroupControl1.touched).toBe(true); }); });
{ "end_byte": 7618, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_array_spec.ts" }
angular/packages/forms/test/form_array_spec.ts_7624_11790
describe('setValue', () => { let c: FormControl, c2: FormControl, a: FormArray; beforeEach(() => { c = new FormControl(''); c2 = new FormControl(''); a = new FormArray([c, c2]); }); it('should set its own value', () => { a.setValue(['one', 'two']); expect(a.value).toEqual(['one', 'two']); }); it('should set child values', () => { a.setValue(['one', 'two']); expect(c.value).toEqual('one'); expect(c2.value).toEqual('two'); }); it('should set values for disabled child controls', () => { c2.disable(); a.setValue(['one', 'two']); expect(c2.value).toEqual('two'); expect(a.value).toEqual(['one']); expect(a.getRawValue()).toEqual(['one', 'two']); }); it('should set value for disabled arrays', () => { a.disable(); a.setValue(['one', 'two']); expect(c.value).toEqual('one'); expect(c2.value).toEqual('two'); expect(a.value).toEqual(['one', 'two']); }); it('should set parent values', () => { const form = new FormGroup({'parent': a}); a.setValue(['one', 'two']); expect(form.value).toEqual({'parent': ['one', 'two']}); }); it('should not update the parent explicitly specified', () => { const form = new FormGroup({'parent': a}); a.setValue(['one', 'two'], {onlySelf: true}); expect(form.value).toEqual({parent: ['', '']}); }); it('should throw if fields are missing from supplied value (subset)', () => { expect(() => a.setValue([, 'two'])).toThrowError( new RegExp(`NG01002: Must supply a value for form control at index: 0`), ); }); it('should throw if a value is provided for a missing control (superset)', () => { expect(() => a.setValue(['one', 'two', 'three'])).toThrowError( new RegExp(`NG01001: Cannot find form control at index: 2`), ); }); it('should throw if a value is not provided for a disabled control', () => { c2.disable(); expect(() => a.setValue(['one'])).toThrowError( new RegExp(`NG01002: Must supply a value for form control at index: 1`), ); }); it('should throw if no controls are set yet', () => { const empty: FormArray = new FormArray<any>([]); expect(() => empty.setValue(['one'])).toThrowError( new RegExp(`no form controls registered with this array`), ); }); describe('setValue() events', () => { let form: FormGroup; let logger: any[]; beforeEach(() => { form = new FormGroup({'parent': a}); logger = []; }); it('should emit one valueChange event per control', () => { form.valueChanges.subscribe(() => logger.push('form')); a.valueChanges.subscribe(() => logger.push('array')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); a.setValue(['one', 'two']); expect(logger).toEqual(['control1', 'control2', 'array', 'form']); }); it('should not fire events when called with `emitEvent: false`', () => { form.valueChanges.subscribe(() => logger.push('form')); a.valueChanges.subscribe(() => logger.push('array')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); a.setValue(['one', 'two'], {emitEvent: false}); expect(logger).toEqual([]); }); it('should emit one statusChange event per control', () => { form.statusChanges.subscribe(() => logger.push('form')); a.statusChanges.subscribe(() => logger.push('array')); c.statusChanges.subscribe(() => logger.push('control1')); c2.statusChanges.subscribe(() => logger.push('control2')); a.setValue(['one', 'two']); expect(logger).toEqual(['control1', 'control2', 'array', 'form']); }); }); });
{ "end_byte": 11790, "start_byte": 7624, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_array_spec.ts" }
angular/packages/forms/test/form_array_spec.ts_11796_16898
describe('patchValue', () => { let c: FormControl, c2: FormControl, a: FormArray, a2: FormArray; beforeEach(() => { c = new FormControl(''); c2 = new FormControl(''); a = new FormArray([c, c2]); a2 = new FormArray([a]); }); it('should set its own value', () => { a.patchValue(['one', 'two']); expect(a.value).toEqual(['one', 'two']); }); it('should set child values', () => { a.patchValue(['one', 'two']); expect(c.value).toEqual('one'); expect(c2.value).toEqual('two'); }); it('should patch disabled control values', () => { c2.disable(); a.patchValue(['one', 'two']); expect(c2.value).toEqual('two'); expect(a.value).toEqual(['one']); expect(a.getRawValue()).toEqual(['one', 'two']); }); it('should patch disabled control arrays', () => { a.disable(); a.patchValue(['one', 'two']); expect(c.value).toEqual('one'); expect(c2.value).toEqual('two'); expect(a.value).toEqual(['one', 'two']); }); it('should set parent values', () => { const form = new FormGroup({'parent': a}); a.patchValue(['one', 'two']); expect(form.value).toEqual({'parent': ['one', 'two']}); }); it('should not update the parent explicitly specified', () => { const form = new FormGroup({'parent': a}); a.patchValue(['one', 'two'], {onlySelf: true}); expect(form.value).toEqual({parent: ['', '']}); }); it('should ignore fields that are missing from supplied value (subset)', () => { a.patchValue([, 'two']); expect(a.value).toEqual(['', 'two']); }); it('should not ignore fields that are null', () => { a.patchValue([null]); expect(a.value).toEqual([null, '']); }); it('should ignore any value provided for a missing control (superset)', () => { a.patchValue([, , 'three']); expect(a.value).toEqual(['', '']); }); it('should ignore a array if `null` or `undefined` are used as values', () => { const INITIAL_STATE = [['', '']]; a2.patchValue([null]); expect(a2.value).toEqual(INITIAL_STATE); a2.patchValue([undefined]); expect(a2.value).toEqual(INITIAL_STATE); }); describe('patchValue() events', () => { let form: FormGroup; let logger: any[]; beforeEach(() => { form = new FormGroup({'parent': a}); logger = []; }); it('should emit one valueChange event per control', () => { form.valueChanges.subscribe(() => logger.push('form')); a.valueChanges.subscribe(() => logger.push('array')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); a.patchValue(['one', 'two']); expect(logger).toEqual(['control1', 'control2', 'array', 'form']); }); it('should not emit valueChange events for skipped controls', () => { form.valueChanges.subscribe(() => logger.push('form')); a.valueChanges.subscribe(() => logger.push('array')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); a.patchValue(['one']); expect(logger).toEqual(['control1', 'array', 'form']); }); it('should not emit valueChange events for skipped controls (represented as `null` or `undefined`)', () => { const logEvent = () => logger.push('valueChanges event'); const [formArrayControl1, formArrayControl2] = (a2.controls as FormArray[])[0].controls; formArrayControl1.valueChanges.subscribe(logEvent); formArrayControl2.valueChanges.subscribe(logEvent); a2.patchValue([null]); a2.patchValue([undefined]); // No events are expected in `valueChanges` since // all controls were skipped in `patchValue`. expect(logger).toEqual([]); }); it('should not fire events when called with `emitEvent: false`', () => { form.valueChanges.subscribe(() => logger.push('form')); a.valueChanges.subscribe(() => logger.push('array')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); a.patchValue(['one', 'two'], {emitEvent: false}); expect(logger).toEqual([]); }); it('should emit one statusChange event per control', () => { form.statusChanges.subscribe(() => logger.push('form')); a.statusChanges.subscribe(() => logger.push('array')); c.statusChanges.subscribe(() => logger.push('control1')); c2.statusChanges.subscribe(() => logger.push('control2')); a.patchValue(['one', 'two']); expect(logger).toEqual(['control1', 'control2', 'array', 'form']); }); }); });
{ "end_byte": 16898, "start_byte": 11796, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_array_spec.ts" }
angular/packages/forms/test/form_array_spec.ts_16904_25679
describe('reset()', () => { let c: FormControl, c2: FormControl, a: FormArray; beforeEach(() => { c = new FormControl('initial value'); c2 = new FormControl(''); a = new FormArray([c, c2]); }); it('should set its own value if value passed', () => { a.setValue(['new value', 'new value']); a.reset(['initial value', '']); expect(a.value).toEqual(['initial value', '']); }); it('should not update the parent when explicitly specified', () => { const form = new FormGroup({'a': a}); a.reset(['one', 'two'], {onlySelf: true}); expect(form.value).toEqual({a: ['initial value', '']}); }); it('should set its own value if boxed value passed', () => { a.setValue(['new value', 'new value']); a.reset([{value: 'initial value', disabled: false}, '']); expect(a.value).toEqual(['initial value', '']); }); it('should clear its own value if no value passed', () => { a.setValue(['new value', 'new value']); a.reset(); expect(a.value).toEqual([null, null]); }); it('should set the value of each of its child controls if value passed', () => { a.setValue(['new value', 'new value']); a.reset(['initial value', '']); expect(c.value).toBe('initial value'); expect(c2.value).toBe(''); }); it('should clear the value of each of its child controls if no value', () => { a.setValue(['new value', 'new value']); a.reset(); expect(c.value).toBe(null); expect(c2.value).toBe(null); }); it('should set the value of its parent if value passed', () => { const form = new FormGroup({'a': a}); a.setValue(['new value', 'new value']); a.reset(['initial value', '']); expect(form.value).toEqual({'a': ['initial value', '']}); }); it('should clear the value of its parent if no value passed', () => { const form = new FormGroup({'a': a}); a.setValue(['new value', 'new value']); a.reset(); expect(form.value).toEqual({'a': [null, null]}); }); it('should mark itself as pristine', () => { a.markAsDirty(); expect(a.pristine).toBe(false); a.reset(); expect(a.pristine).toBe(true); }); it('should mark all child controls as pristine', () => { c.markAsDirty(); c2.markAsDirty(); expect(c.pristine).toBe(false); expect(c2.pristine).toBe(false); a.reset(); expect(c.pristine).toBe(true); expect(c2.pristine).toBe(true); }); it('should mark the parent as pristine if all siblings pristine', () => { const c3 = new FormControl(''); const form = new FormGroup({'a': a, 'c3': c3}); a.markAsDirty(); expect(form.pristine).toBe(false); a.reset(); expect(form.pristine).toBe(true); }); it('should not mark the parent pristine if any dirty siblings', () => { const c3 = new FormControl(''); const form = new FormGroup({'a': a, 'c3': c3}); a.markAsDirty(); c3.markAsDirty(); expect(form.pristine).toBe(false); a.reset(); expect(form.pristine).toBe(false); }); it('should mark itself as untouched', () => { a.markAsTouched(); expect(a.untouched).toBe(false); a.reset(); expect(a.untouched).toBe(true); }); it('should mark all child controls as untouched', () => { c.markAsTouched(); c2.markAsTouched(); expect(c.untouched).toBe(false); expect(c2.untouched).toBe(false); a.reset(); expect(c.untouched).toBe(true); expect(c2.untouched).toBe(true); }); it('should mark the parent untouched if all siblings untouched', () => { const c3 = new FormControl(''); const form = new FormGroup({'a': a, 'c3': c3}); a.markAsTouched(); expect(form.untouched).toBe(false); a.reset(); expect(form.untouched).toBe(true); }); it('should not mark the parent untouched if any touched siblings', () => { const c3 = new FormControl(''); const form = new FormGroup({'a': a, 'c3': c3}); a.markAsTouched(); c3.markAsTouched(); expect(form.untouched).toBe(false); a.reset(); expect(form.untouched).toBe(false); }); it('should retain previous disabled state', () => { a.disable(); a.reset(); expect(a.disabled).toBe(true); }); it('should set child disabled state if boxed value passed', () => { a.disable(); a.reset([{value: '', disabled: false}, '']); expect(c.disabled).toBe(false); expect(a.disabled).toBe(false); }); describe('reset() events', () => { let form: FormGroup, c3: FormControl, logger: any[]; beforeEach(() => { c3 = new FormControl(''); form = new FormGroup({'a': a, 'c3': c3}); logger = []; }); it('should emit one valueChange event per reset control', () => { form.valueChanges.subscribe(() => logger.push('form')); a.valueChanges.subscribe(() => logger.push('array')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); c3.valueChanges.subscribe(() => logger.push('control3')); a.reset(); expect(logger).toEqual(['control1', 'control2', 'array', 'form']); }); it('should not fire events when called with `emitEvent: false`', () => { form.valueChanges.subscribe(() => logger.push('form')); a.valueChanges.subscribe(() => logger.push('array')); c.valueChanges.subscribe(() => logger.push('control1')); c2.valueChanges.subscribe(() => logger.push('control2')); c3.valueChanges.subscribe(() => logger.push('control3')); a.reset([], {emitEvent: false}); expect(logger).toEqual([]); }); it('should emit one statusChange event per reset control', () => { form.statusChanges.subscribe(() => logger.push('form')); a.statusChanges.subscribe(() => logger.push('array')); c.statusChanges.subscribe(() => logger.push('control1')); c2.statusChanges.subscribe(() => logger.push('control2')); c3.statusChanges.subscribe(() => logger.push('control3')); a.reset(); expect(logger).toEqual(['control1', 'control2', 'array', 'form']); }); it('should mark as pristine and not dirty before emitting valueChange and statusChange events when resetting', () => { const pristineAndNotDirty = () => { expect(a.pristine).toBe(true); expect(a.dirty).toBe(false); }; c2.markAsDirty(); expect(a.pristine).toBe(false); expect(a.dirty).toBe(true); a.valueChanges.subscribe(pristineAndNotDirty); a.statusChanges.subscribe(pristineAndNotDirty); a.reset(); }); }); }); describe('errors', () => { it('should run the validator when the value changes', () => { const simpleValidator = (c: FormArray) => c.controls[0].value != 'correct' ? {'broken': true} : null; const c = new FormControl(''); const g = new FormArray([c], simpleValidator as ValidatorFn); c.setValue('correct'); expect(g.valid).toEqual(true); expect(g.errors).toEqual(null); c.setValue('incorrect'); expect(g.valid).toEqual(false); expect(g.errors).toEqual({'broken': true}); }); }); describe('dirty', () => { let c: FormControl; let a: FormArray; beforeEach(() => { c = new FormControl('value'); a = new FormArray([c]); }); it('should be false after creating a control', () => { expect(a.dirty).toEqual(false); }); it('should be true after changing the value of the control', () => { c.markAsDirty(); expect(a.dirty).toEqual(true); }); }); describe('touched', () => { let c: FormControl; let a: FormArray; beforeEach(() => { c = new FormControl('value'); a = new FormArray([c]); }); it('should be false after creating a control', () => { expect(a.touched).toEqual(false); }); it('should be true after child control is marked as touched', () => { c.markAsTouched(); expect(a.touched).toEqual(true); }); });
{ "end_byte": 25679, "start_byte": 16904, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_array_spec.ts" }
angular/packages/forms/test/form_array_spec.ts_25685_34521
describe('pending', () => { let c: FormControl; let a: FormArray; beforeEach(() => { c = new FormControl('value'); a = new FormArray([c]); }); it('should be false after creating a control', () => { expect(c.pending).toEqual(false); expect(a.pending).toEqual(false); }); it('should be true after changing the value of the control', () => { c.markAsPending(); expect(c.pending).toEqual(true); expect(a.pending).toEqual(true); }); it('should not update the parent when onlySelf = true', () => { c.markAsPending({onlySelf: true}); expect(c.pending).toEqual(true); expect(a.pending).toEqual(false); }); describe('status change events', () => { let logger: string[]; beforeEach(() => { logger = []; a.statusChanges.subscribe((status) => logger.push(status)); }); it('should emit event after marking control as pending', () => { c.markAsPending(); expect(logger).toEqual(['PENDING']); }); it('should not emit event from parent when onlySelf is true', () => { c.markAsPending({onlySelf: true}); expect(logger).toEqual([]); }); it('should not emit events when called with `emitEvent: false`', () => { c.markAsPending({emitEvent: false}); expect(logger).toEqual([]); }); it('should emit event when parent is markedAsPending', () => { a.markAsPending(); expect(logger).toEqual(['PENDING']); }); }); }); describe('valueChanges', () => { let a: FormArray; let c1: FormControl, c2: FormControl; beforeEach(() => { c1 = new FormControl('old1'); c2 = new FormControl('old2'); a = new FormArray([c1, c2]); }); it('should fire an event after the value has been updated', (done) => { a.valueChanges.subscribe({ next: (value: any) => { expect(a.value).toEqual(['new1', 'old2']); expect(value).toEqual(['new1', 'old2']); done(); }, }); c1.setValue('new1'); }); it("should fire an event after the control's observable fired an event", (done) => { let controlCallbackIsCalled = false; c1.valueChanges.subscribe({ next: (value: any) => { controlCallbackIsCalled = true; }, }); a.valueChanges.subscribe({ next: (value: any) => { expect(controlCallbackIsCalled).toBe(true); done(); }, }); c1.setValue('new1'); }); it('should fire an event when a control is removed', (done) => { a.valueChanges.subscribe({ next: (value: any) => { expect(value).toEqual(['old1']); done(); }, }); a.removeAt(1); }); it('should fire an event when a control is added', (done) => { a.removeAt(1); a.valueChanges.subscribe({ next: (value: any) => { expect(value).toEqual(['old1', 'old2']); done(); }, }); a.push(c2); }); }); describe('get', () => { it('should return null when path is null', () => { const g = new FormGroup({}); expect(g.get(null!)).toEqual(null); }); it('should return null when path is empty', () => { const g = new FormGroup({}); expect(g.get([])).toEqual(null); }); it('should return null when path is invalid', () => { const g = new FormGroup({}); expect(g.get('invalid')).toEqual(null); }); it('should return a child of a control group', () => { const g = new FormGroup({ 'one': new FormControl('111'), 'nested': new FormGroup({'two': new FormControl('222')}), }); expect(g.get(['one'])!.value).toEqual('111'); expect(g.get('one')!.value).toEqual('111'); expect(g.get(['nested', 'two'])!.value).toEqual('222'); expect(g.get('nested.two')!.value).toEqual('222'); }); it('should return an element of an array', () => { const g = new FormGroup({'array': new FormArray([new FormControl('111')])}); expect(g.get(['array', 0])!.value).toEqual('111'); }); }); describe('validator', () => { function simpleValidator(c: AbstractControl): ValidationErrors | null { return c.get([0])!.value === 'correct' ? null : {'broken': true}; } function arrayRequiredValidator(c: AbstractControl): ValidationErrors | null { return Validators.required(c.get([0]) as AbstractControl); } it('should set a single validator', () => { const a = new FormArray([new FormControl()], simpleValidator); expect(a.valid).toBe(false); expect(a.errors).toEqual({'broken': true}); a.setValue(['correct']); expect(a.valid).toBe(true); }); it('should set a single validator from options obj', () => { const a = new FormArray([new FormControl()], {validators: simpleValidator}); expect(a.valid).toBe(false); expect(a.errors).toEqual({'broken': true}); a.setValue(['correct']); expect(a.valid).toBe(true); }); it('should set multiple validators from an array', () => { const a = new FormArray([new FormControl()], [simpleValidator, arrayRequiredValidator]); expect(a.valid).toBe(false); expect(a.errors).toEqual({'required': true, 'broken': true}); a.setValue(['c']); expect(a.valid).toBe(false); expect(a.errors).toEqual({'broken': true}); a.setValue(['correct']); expect(a.valid).toBe(true); }); it('should set multiple validators from options obj', () => { const a = new FormArray([new FormControl()], { validators: [simpleValidator, arrayRequiredValidator], }); expect(a.valid).toBe(false); expect(a.errors).toEqual({'required': true, 'broken': true}); a.setValue(['c']); expect(a.valid).toBe(false); expect(a.errors).toEqual({'broken': true}); a.setValue(['correct']); expect(a.valid).toBe(true); }); }); describe('asyncValidator', () => { function otherObservableValidator() { return of({'other': true}); } it('should run the async validator', fakeAsync(() => { const c = new FormControl('value'); const g = new FormArray([c], null!, asyncValidator('expected')); expect(g.pending).toEqual(true); tick(); expect(g.errors).toEqual({'async': true}); expect(g.pending).toEqual(false); })); it('should set a single async validator from options obj', fakeAsync(() => { const g = new FormArray([new FormControl('value')], { asyncValidators: asyncValidator('expected'), }); expect(g.pending).toEqual(true); tick(); expect(g.errors).toEqual({'async': true}); expect(g.pending).toEqual(false); })); it('should set multiple async validators from an array', fakeAsync(() => { const g = new FormArray([new FormControl('value')], null!, [ asyncValidator('expected'), otherObservableValidator, ]); expect(g.pending).toEqual(true); tick(); expect(g.errors).toEqual({'async': true, 'other': true}); expect(g.pending).toEqual(false); })); it('should set multiple async validators from options obj', fakeAsync(() => { const g = new FormArray([new FormControl('value')], { asyncValidators: [asyncValidator('expected'), otherObservableValidator], }); expect(g.pending).toEqual(true); tick(); expect(g.errors).toEqual({'async': true, 'other': true}); expect(g.pending).toEqual(false); })); it('should fire statusChanges events when async validators are added via options object', fakeAsync(() => { // The behavior is tested (in other spec files) for each of the model types (`FormControl`, // `FormGroup` and `FormArray`). let statuses: string[] = []; // Create a form control with an async validator added via options object. const asc = new FormArray([], {asyncValidators: [() => Promise.resolve(null)]}); // Subscribe to status changes. asc.statusChanges.subscribe((status: any) => statuses.push(status)); // After a tick, the async validator should change status PENDING -> VALID. tick(); expect(statuses).toEqual(['VALID']); })); });
{ "end_byte": 34521, "start_byte": 25685, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_array_spec.ts" }
angular/packages/forms/test/form_array_spec.ts_34527_43907
describe('disable() & enable()', () => { let a: FormArray; let c: FormControl; let c2: FormControl; beforeEach(() => { c = new FormControl(null); c2 = new FormControl(null); a = new FormArray([c, c2]); }); it('should mark the array as disabled', () => { expect(a.disabled).toBe(false); expect(a.valid).toBe(true); a.disable(); expect(a.disabled).toBe(true); expect(a.valid).toBe(false); a.enable(); expect(a.disabled).toBe(false); expect(a.valid).toBe(true); }); it('should set the array status as disabled', () => { expect(a.status).toBe('VALID'); a.disable(); expect(a.status).toBe('DISABLED'); a.enable(); expect(a.status).toBe('VALID'); }); it('should mark children of the array as disabled', () => { expect(c.disabled).toBe(false); expect(c2.disabled).toBe(false); a.disable(); expect(c.disabled).toBe(true); expect(c2.disabled).toBe(true); a.enable(); expect(c.disabled).toBe(false); expect(c2.disabled).toBe(false); }); it('should ignore disabled controls in validation', () => { const g = new FormGroup({ nested: new FormArray([new FormControl(null, Validators.required)]), two: new FormControl('two'), }); expect(g.valid).toBe(false); g.get('nested')!.disable(); expect(g.valid).toBe(true); g.get('nested')!.enable(); expect(g.valid).toBe(false); }); it('should ignore disabled controls when serializing value', () => { const g = new FormGroup({ nested: new FormArray([new FormControl('one')]), two: new FormControl('two'), }); expect(g.value).toEqual({'nested': ['one'], 'two': 'two'}); g.get('nested')!.disable(); expect(g.value).toEqual({'two': 'two'}); g.get('nested')!.enable(); expect(g.value).toEqual({'nested': ['one'], 'two': 'two'}); }); it('should ignore disabled controls when determining dirtiness', () => { const g = new FormGroup({nested: a, two: new FormControl('two')}); g.get(['nested', 0])!.markAsDirty(); expect(g.dirty).toBe(true); g.get('nested')!.disable(); expect(g.get('nested')!.dirty).toBe(true); expect(g.dirty).toEqual(false); g.get('nested')!.enable(); expect(g.dirty).toEqual(true); }); it('should ignore disabled controls when determining touched state', () => { const g = new FormGroup({nested: a, two: new FormControl('two')}); g.get(['nested', 0])!.markAsTouched(); expect(g.touched).toBe(true); g.get('nested')!.disable(); expect(g.get('nested')!.touched).toBe(true); expect(g.touched).toEqual(false); g.get('nested')!.enable(); expect(g.touched).toEqual(true); }); it('should keep empty, disabled arrays disabled when updating validity', () => { const arr: FormArray = new FormArray<any>([]); expect(arr.status).toEqual('VALID'); arr.disable(); expect(arr.status).toEqual('DISABLED'); arr.updateValueAndValidity(); expect(arr.status).toEqual('DISABLED'); arr.push(new FormControl({value: '', disabled: true})); expect(arr.status).toEqual('DISABLED'); arr.push(new FormControl()); expect(arr.status).toEqual('VALID'); }); it('should re-enable empty, disabled arrays', () => { const arr = new FormArray([]); arr.disable(); expect(arr.status).toEqual('DISABLED'); arr.enable(); expect(arr.status).toEqual('VALID'); }); it('should not run validators on disabled controls', () => { const validator = jasmine.createSpy('validator'); const arr = new FormArray([new FormControl()], validator); expect(validator.calls.count()).toEqual(1); arr.disable(); expect(validator.calls.count()).toEqual(1); arr.setValue(['value']); expect(validator.calls.count()).toEqual(1); arr.enable(); expect(validator.calls.count()).toEqual(2); }); describe('disabled errors', () => { it('should clear out array errors when disabled', () => { const arr = new FormArray([new FormControl()], () => ({'expected': true})); expect(arr.errors).toEqual({'expected': true}); arr.disable(); expect(arr.errors).toEqual(null); arr.enable(); expect(arr.errors).toEqual({'expected': true}); }); it('should re-populate array errors when enabled from a child', () => { const arr = new FormArray([new FormControl()], () => ({'expected': true})); arr.disable(); expect(arr.errors).toEqual(null); arr.push(new FormControl()); expect(arr.errors).toEqual({'expected': true}); }); it('should clear out async array errors when disabled', fakeAsync(() => { const arr = new FormArray([new FormControl()], null!, asyncValidator('expected')); tick(); expect(arr.errors).toEqual({'async': true}); arr.disable(); expect(arr.errors).toEqual(null); arr.enable(); tick(); expect(arr.errors).toEqual({'async': true}); })); it('should re-populate async array errors when enabled from a child', fakeAsync(() => { const arr = new FormArray([new FormControl()], null!, asyncValidator('expected')); tick(); expect(arr.errors).toEqual({'async': true}); arr.disable(); expect(arr.errors).toEqual(null); arr.push(new FormControl()); tick(); expect(arr.errors).toEqual({'async': true}); })); }); describe('disabled events', () => { let logger: string[]; let c: FormControl; let a: FormArray; let form: FormGroup; beforeEach(() => { logger = []; c = new FormControl('', Validators.required); a = new FormArray([c]); form = new FormGroup({a: a}); }); it('should emit value change events in the right order', () => { c.valueChanges.subscribe(() => logger.push('control')); a.valueChanges.subscribe(() => logger.push('array')); form.valueChanges.subscribe(() => logger.push('form')); a.disable(); expect(logger).toEqual(['control', 'array', 'form']); }); it('should emit status change events in the right order', () => { c.statusChanges.subscribe(() => logger.push('control')); a.statusChanges.subscribe(() => logger.push('array')); form.statusChanges.subscribe(() => logger.push('form')); a.disable(); expect(logger).toEqual(['control', 'array', 'form']); }); it('should not emit value change events when called with `emitEvent: false`', () => { c.valueChanges.subscribe(() => logger.push('control')); a.valueChanges.subscribe(() => logger.push('array')); form.valueChanges.subscribe(() => logger.push('form')); a.disable({emitEvent: false}); expect(logger).toEqual([]); a.enable({emitEvent: false}); expect(logger).toEqual([]); }); it('should not emit status change events when called with `emitEvent: false`', () => { c.statusChanges.subscribe(() => logger.push('control')); a.statusChanges.subscribe(() => logger.push('array')); form.statusChanges.subscribe(() => logger.push('form')); a.disable({emitEvent: false}); expect(logger).toEqual([]); a.enable({emitEvent: false}); expect(logger).toEqual([]); }); }); describe('setControl()', () => { let c: FormControl; let a: FormArray; beforeEach(() => { c = new FormControl('one'); a = new FormArray([c]); }); it('should replace existing control with new control', () => { const c2 = new FormControl('new!', Validators.minLength(10)); a.setControl(0, c2); expect(a.controls[0]).toEqual(c2); expect(a.value).toEqual(['new!']); expect(a.valid).toBe(false); }); it('should add control if control did not exist before', () => { const c2 = new FormControl('new!', Validators.minLength(10)); a.setControl(1, c2); expect(a.controls[1]).toEqual(c2); expect(a.value).toEqual(['one', 'new!']); expect(a.valid).toBe(false); }); it('should remove control if new control is null', () => { a.setControl(0, null!); expect(a.controls[0]).not.toBeDefined(); expect(a.value).toEqual([]); }); it('should only emit value change event once', () => { const logger: string[] = []; const c2 = new FormControl('new!'); a.valueChanges.subscribe(() => logger.push('change!')); a.setControl(0, c2); expect(logger).toEqual(['change!']); }); }); });
{ "end_byte": 43907, "start_byte": 34527, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_array_spec.ts" }
angular/packages/forms/test/form_array_spec.ts_43913_50032
describe('out of bounds positive indices', () => { let c1: FormControl = new FormControl(1); let c2: FormControl = new FormControl(2); let c3: FormControl = new FormControl(3); let c4: FormControl = new FormControl(4); let c99: FormControl = new FormControl(99); let fa: FormArray; beforeEach(() => { fa = new FormArray([c1, c2, c3, c4]); }); // This spec checks the behavior is identical to `Array.prototype.at(index)` it('should work with at', () => { expect(fa.at(4)).toBeUndefined(); }); // This spec checks the behavior is identical to `Array.prototype.splice(index, 1, ...)` it('should work with setControl', () => { fa.setControl(4, c99); expect(fa.value).toEqual([1, 2, 3, 4, 99]); }); // This spec checks the behavior is identical to `Array.prototype.splice(index, 1)` it('should work with removeAt', () => { fa.removeAt(4); expect(fa.value).toEqual([1, 2, 3, 4]); }); // This spec checks the behavior is identical to `Array.prototype.splice(index, 0, ...)` it('should work with insert', () => { fa.insert(4, c99); expect(fa.value).toEqual([1, 2, 3, 4, 99]); }); }); describe('negative indices', () => { let c1: FormControl = new FormControl(1); let c2: FormControl = new FormControl(2); let c3: FormControl = new FormControl(3); let c4: FormControl = new FormControl(4); let c99: FormControl = new FormControl(99); let fa: FormArray; beforeEach(() => { fa = new FormArray([c1, c2, c3, c4]); }); // This spec checks the behavior is identical to `Array.prototype.at(index)` describe('should work with at', () => { it('wrapping from the back between [-length, 0)', () => { expect(fa.at(-1)).toBe(c4); expect(fa.at(-2)).toBe(c3); expect(fa.at(-3)).toBe(c2); expect(fa.at(-4)).toBe(c1); }); it('becoming undefined when less than -length', () => { expect(fa.at(-5)).toBeUndefined(); expect(fa.at(-10)).toBeUndefined(); }); }); // This spec checks the behavior is identical to `Array.prototype.splice(index, 1, ...)` describe('should work with setControl', () => { describe('wrapping from the back between [-length, 0)', () => { it('at -1', () => { fa.setControl(-1, c99); expect(fa.value).toEqual([1, 2, 3, 99]); }); it('at -2', () => { fa.setControl(-2, c99); expect(fa.value).toEqual([1, 2, 99, 4]); }); it('at -3', () => { fa.setControl(-3, c99); expect(fa.value).toEqual([1, 99, 3, 4]); }); it('at -4', () => { fa.setControl(-4, c99); expect(fa.value).toEqual([99, 2, 3, 4]); }); }); describe('replacing the first item when less than -length', () => { it('at -5', () => { fa.setControl(-5, c99); expect(fa.value).toEqual([99, 2, 3, 4]); }); it('at -10', () => { fa.setControl(-10, c99); expect(fa.value).toEqual([99, 2, 3, 4]); }); }); }); // This spec checks the behavior is identical to `Array.prototype.splice(index, 1)` describe('should work with removeAt', () => { describe('wrapping from the back between [-length, 0)', () => { it('at -1', () => { fa.removeAt(-1); expect(fa.value).toEqual([1, 2, 3]); }); it('at -2', () => { fa.removeAt(-2); expect(fa.value).toEqual([1, 2, 4]); }); it('at -3', () => { fa.removeAt(-3); expect(fa.value).toEqual([1, 3, 4]); }); it('at -4', () => { fa.removeAt(-4); expect(fa.value).toEqual([2, 3, 4]); }); }); describe('removing the first item when less than -length', () => { it('at -5', () => { fa.removeAt(-5); expect(fa.value).toEqual([2, 3, 4]); }); it('at -10', () => { fa.removeAt(-10); expect(fa.value).toEqual([2, 3, 4]); }); }); }); // This spec checks the behavior is identical to `Array.prototype.splice(index, 0, ...)` describe('should work with insert', () => { describe('wrapping from the back between [-length, 0)', () => { it('at -1', () => { fa.insert(-1, c99); expect(fa.value).toEqual([1, 2, 3, 99, 4]); }); it('at -2', () => { fa.insert(-2, c99); expect(fa.value).toEqual([1, 2, 99, 3, 4]); }); it('at -3', () => { fa.insert(-3, c99); expect(fa.value).toEqual([1, 99, 2, 3, 4]); }); it('at -4', () => { fa.insert(-4, c99); expect(fa.value).toEqual([99, 1, 2, 3, 4]); }); }); describe('prepending when less than -length', () => { it('at -5', () => { fa.insert(-5, c99); expect(fa.value).toEqual([99, 1, 2, 3, 4]); }); it('at -10', () => { fa.insert(-10, c99); expect(fa.value).toEqual([99, 1, 2, 3, 4]); }); }); describe('can be extended', () => { it('by a simple strongly-typed array', () => { abstract class StringFormArray extends FormArray { override value: string[] = []; } }); it('by a class that redefines many properties', () => { abstract class OtherTypedFormArray< TControls extends Array<AbstractControl<unknown>>, > extends FormArray { override controls: TControls = {} as TControls; override value: string[] = []; } }); }); }); }); }); })();
{ "end_byte": 50032, "start_byte": 43913, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_array_spec.ts" }
angular/packages/forms/test/directives_spec.ts_0_5207
/** * @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 {SimpleChange, ɵWritable as Writable} from '@angular/core'; import {fakeAsync, flushMicrotasks, tick} from '@angular/core/testing'; import { AbstractControl, CheckboxControlValueAccessor, ControlValueAccessor, DefaultValueAccessor, FormArray, FormArrayName, FormControl, FormControlDirective, FormControlName, FormGroup, FormGroupDirective, FormGroupName, NgControl, NgForm, NgModel, NgModelGroup, SelectControlValueAccessor, SelectMultipleControlValueAccessor, ValidationErrors, Validator, Validators, } from '@angular/forms'; import {selectValueAccessor} from '@angular/forms/src/directives/shared'; import {composeValidators} from '@angular/forms/src/validators'; import {asyncValidator} from './util'; class DummyControlValueAccessor implements ControlValueAccessor { writtenValue: any; registerOnChange(fn: any) {} registerOnTouched(fn: any) {} writeValue(obj: any): void { this.writtenValue = obj; } } class CustomValidatorDirective implements Validator { validate(c: FormControl): ValidationErrors { return {'custom': true}; } } describe('Form Directives', () => { let defaultAccessor: DefaultValueAccessor; beforeEach(() => { defaultAccessor = new DefaultValueAccessor(null!, null!, null!); }); describe('shared', () => { describe('selectValueAccessor', () => { let dir: NgControl; beforeEach(() => { dir = {path: []} as any; }); it('should throw when given an empty array', () => { expect(() => selectValueAccessor(dir, [])).toThrowError(); }); it('should throw when accessor is not provided as array', () => { expect(() => selectValueAccessor(dir, {} as any[])).toThrowError( 'NG01200: Value accessor was not provided as an array for form control with unspecified name attribute. Check that the `NG_VALUE_ACCESSOR` token is configured as a `multi: true` provider.', ); }); it('should return the default value accessor when no other provided', () => { expect(selectValueAccessor(dir, [defaultAccessor])).toEqual(defaultAccessor); }); it('should return checkbox accessor when provided', () => { const checkboxAccessor = new CheckboxControlValueAccessor(null!, null!); expect(selectValueAccessor(dir, [defaultAccessor, checkboxAccessor])).toEqual( checkboxAccessor, ); }); it('should return select accessor when provided', () => { const selectAccessor = new SelectControlValueAccessor(null!, null!); expect(selectValueAccessor(dir, [defaultAccessor, selectAccessor])).toEqual(selectAccessor); }); it('should return select multiple accessor when provided', () => { const selectMultipleAccessor = new SelectMultipleControlValueAccessor(null!, null!); expect(selectValueAccessor(dir, [defaultAccessor, selectMultipleAccessor])).toEqual( selectMultipleAccessor, ); }); it('should throw when more than one build-in accessor is provided', () => { const checkboxAccessor = new CheckboxControlValueAccessor(null!, null!); const selectAccessor = new SelectControlValueAccessor(null!, null!); expect(() => selectValueAccessor(dir, [checkboxAccessor, selectAccessor])).toThrowError(); }); it('should return custom accessor when provided', () => { const customAccessor: ControlValueAccessor = {} as any; const checkboxAccessor = new CheckboxControlValueAccessor(null!, null!); expect( selectValueAccessor(dir, <any>[defaultAccessor, customAccessor, checkboxAccessor]), ).toEqual(customAccessor); }); it('should return custom accessor when provided with select multiple', () => { const customAccessor: ControlValueAccessor = {} as any; const selectMultipleAccessor = new SelectMultipleControlValueAccessor(null!, null!); expect( selectValueAccessor(dir, <any>[defaultAccessor, customAccessor, selectMultipleAccessor]), ).toEqual(customAccessor); }); it('should throw when more than one custom accessor is provided', () => { const customAccessor: ControlValueAccessor = {} as any; expect(() => selectValueAccessor(dir, [customAccessor, customAccessor])).toThrowError(); }); }); describe('composeValidators', () => { it('should compose functions', () => { const dummy1 = () => ({'dummy1': true}); const dummy2 = () => ({'dummy2': true}); const v = composeValidators([dummy1, dummy2])!; expect(v(new FormControl(''))).toEqual({'dummy1': true, 'dummy2': true}); }); it('should compose validator directives', () => { const dummy1 = () => ({'dummy1': true}); const v = composeValidators([dummy1, new CustomValidatorDirective()])!; expect(v(new FormControl(''))).toEqual({'dummy1': true, 'custom': true}); }); }); });
{ "end_byte": 5207, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/directives_spec.ts" }
angular/packages/forms/test/directives_spec.ts_5211_12049
escribe('formGroup', () => { let form: FormGroupDirective; let formModel: FormGroup; let loginControlDir: FormControlName; beforeEach(() => { form = new FormGroupDirective([], []); formModel = new FormGroup({ 'login': new FormControl(), 'passwords': new FormGroup({ 'password': new FormControl(), 'passwordConfirm': new FormControl(), }), }); form.form = formModel; loginControlDir = new FormControlName( form, [Validators.required], [asyncValidator('expected')], [defaultAccessor], null, ); loginControlDir.name = 'login'; loginControlDir.valueAccessor = new DummyControlValueAccessor(); }); it('should reexport control properties', () => { expect(form.control).toBe(formModel); expect(form.value).toBe(formModel.value); expect(form.valid).toBe(formModel.valid); expect(form.invalid).toBe(formModel.invalid); expect(form.pending).toBe(formModel.pending); expect(form.errors).toBe(formModel.errors); expect(form.pristine).toBe(formModel.pristine); expect(form.dirty).toBe(formModel.dirty); expect(form.touched).toBe(formModel.touched); expect(form.untouched).toBe(formModel.untouched); expect(form.statusChanges).toBe(formModel.statusChanges); expect(form.valueChanges).toBe(formModel.valueChanges); }); it('should reexport control methods', () => { expect(form.hasError('required')).toBe(formModel.hasError('required')); expect(form.getError('required')).toBe(formModel.getError('required')); formModel.setErrors({required: true}); expect(form.hasError('required')).toBe(formModel.hasError('required')); expect(form.getError('required')).toBe(formModel.getError('required')); }); describe('addControl', () => { it('should throw when no control found', () => { const dir = new FormControlName(form, null!, null!, [defaultAccessor], null); dir.name = 'invalidName'; expect(() => form.addControl(dir)).toThrowError( new RegExp(`Cannot find control with name: 'invalidName'`), ); }); it('should throw for a named control when no value accessor', () => { const dir = new FormControlName(form, null!, null!, null!, null); dir.name = 'login'; expect(() => form.addControl(dir)).toThrowError( new RegExp( `NG01203: No value accessor for form control name: 'login'. Find more at https://angular.dev/errors/NG01203`, ), ); }); it('should throw when no value accessor with path', () => { const group = new FormGroupName(form, null!, null!); const dir = new FormControlName(group, null!, null!, null!, null); group.name = 'passwords'; dir.name = 'password'; expect(() => form.addControl(dir)).toThrowError( new RegExp( `NG01203: No value accessor for form control path: 'passwords -> password'. Find more at https://angular.dev/errors/NG01203`, ), ); }); it('should set up validators', fakeAsync(() => { form.addControl(loginControlDir); // sync validators are set expect(formModel.hasError('required', ['login'])).toBe(true); expect(formModel.hasError('async', ['login'])).toBe(false); (<FormControl>formModel.get('login')).setValue('invalid value'); // sync validator passes, running async validators expect(formModel.pending).toBe(true); tick(); expect(formModel.hasError('required', ['login'])).toBe(false); expect(formModel.hasError('async', ['login'])).toBe(true); })); it('should write value to the DOM', () => { (<FormControl>formModel.get(['login'])).setValue('initValue'); form.addControl(loginControlDir); expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('initValue'); }); it('should add the directive to the list of directives included in the form', () => { form.addControl(loginControlDir); expect(form.directives).toEqual([loginControlDir]); }); }); describe('addFormGroup', () => { const matchingPasswordsValidator = (g: AbstractControl) => { const controls = (g as FormGroup).controls; if (controls['password'].value != controls['passwordConfirm'].value) { return {'differentPasswords': true}; } else { return null; } }; it('should set up validator', fakeAsync(() => { const group = new FormGroupName( form, [matchingPasswordsValidator], [asyncValidator('expected')], ); group.name = 'passwords'; form.addFormGroup(group); (<FormControl>formModel.get(['passwords', 'password'])).setValue('somePassword'); (<FormControl>formModel.get(['passwords', 'passwordConfirm'])).setValue( 'someOtherPassword', ); // sync validators are set expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true); (<FormControl>formModel.get(['passwords', 'passwordConfirm'])).setValue('somePassword'); // sync validators pass, running async validators expect(formModel.pending).toBe(true); tick(); expect(formModel.hasError('async', ['passwords'])).toBe(true); })); }); describe('removeControl', () => { it('should remove the directive to the list of directives included in the form', () => { form.addControl(loginControlDir); form.removeControl(loginControlDir); expect(form.directives).toEqual([]); }); }); describe('ngOnChanges', () => { it('should update dom values of all the directives', () => { form.addControl(loginControlDir); (<FormControl>formModel.get(['login'])).setValue('new value'); form.ngOnChanges({}); expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('new value'); }); it('should set up a sync validator', () => { const formValidator = (c: AbstractControl) => ({'custom': true}); const f = new FormGroupDirective([formValidator], []); f.form = formModel; f.ngOnChanges({'form': new SimpleChange(null, null, false)}); expect(formModel.errors).toEqual({'custom': true}); }); it('should set up an async validator', fakeAsync(() => { const f = new FormGroupDirective([], [asyncValidator('expected')]); f.form = formModel; f.ngOnChanges({'form': new SimpleChange(null, null, false)}); tick(); expect(formModel.errors).toEqual({'async': true}); })); }); });
{ "end_byte": 12049, "start_byte": 5211, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/directives_spec.ts" }
angular/packages/forms/test/directives_spec.ts_12053_21191
escribe('NgForm', () => { let form: NgForm; let formModel: FormGroup; let loginControlDir: NgModel; let personControlGroupDir: NgModelGroup; beforeEach(() => { form = new NgForm([], []); formModel = form.form; personControlGroupDir = new NgModelGroup(form, [], []); personControlGroupDir.name = 'person'; loginControlDir = new NgModel(personControlGroupDir, null!, null!, [defaultAccessor]); loginControlDir.name = 'login'; loginControlDir.valueAccessor = new DummyControlValueAccessor(); }); it('should reexport control properties', () => { expect(form.control).toBe(formModel); expect(form.value).toBe(formModel.value); expect(form.valid).toBe(formModel.valid); expect(form.invalid).toBe(formModel.invalid); expect(form.pending).toBe(formModel.pending); expect(form.errors).toBe(formModel.errors); expect(form.pristine).toBe(formModel.pristine); expect(form.dirty).toBe(formModel.dirty); expect(form.touched).toBe(formModel.touched); expect(form.untouched).toBe(formModel.untouched); expect(form.statusChanges).toBe(formModel.statusChanges); expect(form.status).toBe(formModel.status); expect(form.valueChanges).toBe(formModel.valueChanges); expect(form.disabled).toBe(formModel.disabled); expect(form.enabled).toBe(formModel.enabled); }); it('should reexport control methods', () => { expect(form.hasError('required')).toBe(formModel.hasError('required')); expect(form.getError('required')).toBe(formModel.getError('required')); formModel.setErrors({required: true}); expect(form.hasError('required')).toBe(formModel.hasError('required')); expect(form.getError('required')).toBe(formModel.getError('required')); }); describe('addControl & addFormGroup', () => { it('should create a control with the given name', fakeAsync(() => { form.addFormGroup(personControlGroupDir); form.addControl(loginControlDir); flushMicrotasks(); expect(formModel.get(['person', 'login'])).not.toBeNull(); })); // should update the form's value and validity }); describe('removeControl & removeFormGroup', () => { it('should remove control', fakeAsync(() => { form.addFormGroup(personControlGroupDir); form.addControl(loginControlDir); form.removeFormGroup(personControlGroupDir); form.removeControl(loginControlDir); flushMicrotasks(); expect(formModel.get(['person'])).toBeNull(); expect(formModel.get(['person', 'login'])).toBeNull(); })); // should update the form's value and validity }); it('should set up sync validator', fakeAsync(() => { const formValidator = () => ({'custom': true}); const f = new NgForm([formValidator], []); tick(); expect(f.form.errors).toEqual({'custom': true}); })); it('should set up async validator', fakeAsync(() => { const f = new NgForm([], [asyncValidator('expected')]); tick(); expect(f.form.errors).toEqual({'async': true}); })); }); describe('FormGroupName', () => { let formModel: FormGroup; let controlGroupDir: FormGroupName; beforeEach(() => { formModel = new FormGroup({'login': new FormControl(null)}); const parent = new FormGroupDirective([], []); parent.form = new FormGroup({'group': formModel}); controlGroupDir = new FormGroupName(parent, [], []); controlGroupDir.name = 'group'; }); it('should reexport control properties', () => { expect(controlGroupDir.control).toBe(formModel); expect(controlGroupDir.value).toBe(formModel.value); expect(controlGroupDir.valid).toBe(formModel.valid); expect(controlGroupDir.invalid).toBe(formModel.invalid); expect(controlGroupDir.pending).toBe(formModel.pending); expect(controlGroupDir.errors).toBe(formModel.errors); expect(controlGroupDir.pristine).toBe(formModel.pristine); expect(controlGroupDir.dirty).toBe(formModel.dirty); expect(controlGroupDir.touched).toBe(formModel.touched); expect(controlGroupDir.untouched).toBe(formModel.untouched); expect(controlGroupDir.statusChanges).toBe(formModel.statusChanges); expect(controlGroupDir.status).toBe(formModel.status); expect(controlGroupDir.valueChanges).toBe(formModel.valueChanges); expect(controlGroupDir.disabled).toBe(formModel.disabled); expect(controlGroupDir.enabled).toBe(formModel.enabled); }); it('should reexport control methods', () => { expect(controlGroupDir.hasError('required')).toBe(formModel.hasError('required')); expect(controlGroupDir.getError('required')).toBe(formModel.getError('required')); formModel.setErrors({required: true}); expect(controlGroupDir.hasError('required')).toBe(formModel.hasError('required')); expect(controlGroupDir.getError('required')).toBe(formModel.getError('required')); }); }); describe('FormArrayName', () => { let formModel: FormArray; let formArrayDir: FormArrayName; beforeEach(() => { const parent = new FormGroupDirective([], []); formModel = new FormArray([new FormControl('')]); parent.form = new FormGroup({'array': formModel}); formArrayDir = new FormArrayName(parent, [], []); formArrayDir.name = 'array'; }); it('should reexport control properties', () => { expect(formArrayDir.control).toBe(formModel); expect(formArrayDir.value).toBe(formModel.value); expect(formArrayDir.valid).toBe(formModel.valid); expect(formArrayDir.invalid).toBe(formModel.invalid); expect(formArrayDir.pending).toBe(formModel.pending); expect(formArrayDir.errors).toBe(formModel.errors); expect(formArrayDir.pristine).toBe(formModel.pristine); expect(formArrayDir.dirty).toBe(formModel.dirty); expect(formArrayDir.touched).toBe(formModel.touched); expect(formArrayDir.status).toBe(formModel.status); expect(formArrayDir.untouched).toBe(formModel.untouched); expect(formArrayDir.disabled).toBe(formModel.disabled); expect(formArrayDir.enabled).toBe(formModel.enabled); }); it('should reexport control methods', () => { expect(formArrayDir.hasError('required')).toBe(formModel.hasError('required')); expect(formArrayDir.getError('required')).toBe(formModel.getError('required')); formModel.setErrors({required: true}); expect(formArrayDir.hasError('required')).toBe(formModel.hasError('required')); expect(formArrayDir.getError('required')).toBe(formModel.getError('required')); }); }); describe('FormControlDirective', () => { let controlDir: FormControlDirective; let control: FormControl; const checkProperties = function (control: FormControl) { expect(controlDir.control).toBe(control); expect(controlDir.value).toBe(control.value); expect(controlDir.valid).toBe(control.valid); expect(controlDir.invalid).toBe(control.invalid); expect(controlDir.pending).toBe(control.pending); expect(controlDir.errors).toBe(control.errors); expect(controlDir.pristine).toBe(control.pristine); expect(controlDir.dirty).toBe(control.dirty); expect(controlDir.touched).toBe(control.touched); expect(controlDir.untouched).toBe(control.untouched); expect(controlDir.statusChanges).toBe(control.statusChanges); expect(controlDir.status).toBe(control.status); expect(controlDir.valueChanges).toBe(control.valueChanges); expect(controlDir.disabled).toBe(control.disabled); expect(controlDir.enabled).toBe(control.enabled); }; beforeEach(() => { controlDir = new FormControlDirective([Validators.required], [], [defaultAccessor], null); controlDir.valueAccessor = new DummyControlValueAccessor(); control = new FormControl(null); controlDir.form = control; }); it('should reexport control properties', () => { checkProperties(control); }); it('should reexport control methods', () => { expect(controlDir.hasError('required')).toBe(control.hasError('required')); expect(controlDir.getError('required')).toBe(control.getError('required')); control.setErrors({required: true}); expect(controlDir.hasError('required')).toBe(control.hasError('required')); expect(controlDir.getError('required')).toBe(control.getError('required')); }); it('should reexport new control properties', () => { const newControl = new FormControl(null); controlDir.form = newControl; controlDir.ngOnChanges({'form': new SimpleChange(control, newControl, false)}); checkProperties(newControl); }); it('should set up validator', () => { expect(control.valid).toBe(true); // this will add the required validator and recalculate the validity controlDir.ngOnChanges({'form': new SimpleChange(null, control, false)}); expect(control.valid).toBe(false); }); });
{ "end_byte": 21191, "start_byte": 12053, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/directives_spec.ts" }
angular/packages/forms/test/directives_spec.ts_21195_27355
escribe('NgModel', () => { let ngModel: NgModel; let control: FormControl; beforeEach(() => { ngModel = new NgModel( null!, [Validators.required], [asyncValidator('expected')], [defaultAccessor], ); ngModel.valueAccessor = new DummyControlValueAccessor(); control = ngModel.control; }); it('should reexport control properties', () => { expect(ngModel.control).toBe(control); expect(ngModel.value).toBe(control.value); expect(ngModel.valid).toBe(control.valid); expect(ngModel.invalid).toBe(control.invalid); expect(ngModel.pending).toBe(control.pending); expect(ngModel.errors).toBe(control.errors); expect(ngModel.pristine).toBe(control.pristine); expect(ngModel.dirty).toBe(control.dirty); expect(ngModel.touched).toBe(control.touched); expect(ngModel.untouched).toBe(control.untouched); expect(ngModel.statusChanges).toBe(control.statusChanges); expect(ngModel.status).toBe(control.status); expect(ngModel.valueChanges).toBe(control.valueChanges); expect(ngModel.disabled).toBe(control.disabled); expect(ngModel.enabled).toBe(control.enabled); }); it('should reexport control methods', () => { expect(ngModel.hasError('required')).toBe(control.hasError('required')); expect(ngModel.getError('required')).toBe(control.getError('required')); control.setErrors({required: true}); expect(ngModel.hasError('required')).toBe(control.hasError('required')); expect(ngModel.getError('required')).toBe(control.getError('required')); }); it('should throw when no value accessor with named control', () => { const namedDir = new NgModel(null!, null!, null!, null!); namedDir.name = 'one'; expect(() => namedDir.ngOnChanges({})).toThrowError( new RegExp( `NG01203: No value accessor for form control name: 'one'. Find more at https://angular.dev/errors/NG01203`, ), ); }); it('should throw when no value accessor with unnamed control', () => { const unnamedDir = new NgModel(null!, null!, null!, null!); expect(() => unnamedDir.ngOnChanges({})).toThrowError( new RegExp( `NG01203: No value accessor for form control unspecified name attribute. Find more at https://angular.dev/errors/NG01203`, ), ); }); it('should set up validator', fakeAsync(() => { // this will add the required validator and recalculate the validity ngModel.ngOnChanges({}); tick(); expect(ngModel.control.errors).toEqual({'required': true}); ngModel.control.setValue('someValue'); tick(); expect(ngModel.control.errors).toEqual({'async': true}); })); it('should mark as disabled properly', fakeAsync(() => { ngModel.ngOnChanges({isDisabled: new SimpleChange('', undefined, false)}); tick(); expect(ngModel.control.disabled).toEqual(false); ngModel.ngOnChanges({isDisabled: new SimpleChange('', null, false)}); tick(); expect(ngModel.control.disabled).toEqual(false); ngModel.ngOnChanges({isDisabled: new SimpleChange('', false, false)}); tick(); expect(ngModel.control.disabled).toEqual(false); ngModel.ngOnChanges({isDisabled: new SimpleChange('', 'false', false)}); tick(); expect(ngModel.control.disabled).toEqual(false); ngModel.ngOnChanges({isDisabled: new SimpleChange('', 0, false)}); tick(); expect(ngModel.control.disabled).toEqual(false); ngModel.ngOnChanges({isDisabled: new SimpleChange(null, '', false)}); tick(); expect(ngModel.control.disabled).toEqual(true); ngModel.ngOnChanges({isDisabled: new SimpleChange(null, 'true', false)}); tick(); expect(ngModel.control.disabled).toEqual(true); ngModel.ngOnChanges({isDisabled: new SimpleChange(null, true, false)}); tick(); expect(ngModel.control.disabled).toEqual(true); ngModel.ngOnChanges({isDisabled: new SimpleChange(null, 'anything else', false)}); tick(); expect(ngModel.control.disabled).toEqual(true); })); }); describe('FormControlName', () => { let formModel: FormControl; let controlNameDir: FormControlName; beforeEach(() => { formModel = new FormControl('name'); const parent = new FormGroupDirective([], []); parent.form = new FormGroup({'name': formModel}); controlNameDir = new FormControlName(parent, [], [], [defaultAccessor], null); controlNameDir.name = 'name'; (controlNameDir as Writable<FormControlName>).control = formModel; }); it('should reexport control properties', () => { expect(controlNameDir.control).toBe(formModel); expect(controlNameDir.value).toBe(formModel.value); expect(controlNameDir.valid).toBe(formModel.valid); expect(controlNameDir.invalid).toBe(formModel.invalid); expect(controlNameDir.pending).toBe(formModel.pending); expect(controlNameDir.errors).toBe(formModel.errors); expect(controlNameDir.pristine).toBe(formModel.pristine); expect(controlNameDir.dirty).toBe(formModel.dirty); expect(controlNameDir.touched).toBe(formModel.touched); expect(controlNameDir.untouched).toBe(formModel.untouched); expect(controlNameDir.statusChanges).toBe(formModel.statusChanges); expect(controlNameDir.status).toBe(formModel.status); expect(controlNameDir.valueChanges).toBe(formModel.valueChanges); expect(controlNameDir.disabled).toBe(formModel.disabled); expect(controlNameDir.enabled).toBe(formModel.enabled); }); it('should reexport control methods', () => { expect(controlNameDir.hasError('required')).toBe(formModel.hasError('required')); expect(controlNameDir.getError('required')).toBe(formModel.getError('required')); formModel.setErrors({required: true}); expect(controlNameDir.hasError('required')).toBe(formModel.hasError('required')); expect(controlNameDir.getError('required')).toBe(formModel.getError('required')); }); }); });
{ "end_byte": 27355, "start_byte": 21195, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/directives_spec.ts" }
angular/packages/forms/test/typed_integration_spec.ts_0_4423
/** * @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 */ // These tests mainly check the types of strongly typed form controls, which is generally enforced // at compile time. import {FormBuilder, NonNullableFormBuilder, UntypedFormBuilder} from '../src/form_builder'; import { AbstractControl, FormArray, FormControl, FormGroup, UntypedFormArray, UntypedFormControl, UntypedFormGroup, Validators, } from '../src/forms'; import {FormRecord} from '../src/model/form_group'; describe('Typed Class', () => { describe('FormControl', () => { it('supports inferred controls', () => { const c = new FormControl('', {nonNullable: true}); { type ValueType = string; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = string; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.setValue(''); // @ts-expect-error c.setValue(null); c.patchValue(''); c.reset(''); }); it('supports explicit controls', () => { const c = new FormControl<string>('', {nonNullable: true}); { type ValueType = string; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = string; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.setValue(''); c.patchValue(''); c.reset(''); }); it('supports explicit boolean controls', () => { let c1: FormControl<boolean> = new FormControl(false, {nonNullable: true}); }); it('supports empty controls', () => { let c = new FormControl(); let ca: FormControl<any> = c; }); it('supports nullable controls', () => { const c = new FormControl<string | null>(''); { type ValueType = string | null; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = string | null; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.setValue(null); c.setValue(''); // @ts-expect-error c.setValue(7); c.patchValue(null); c.patchValue(''); c.reset(); c.reset(''); }); it('should create a nullable control without {nonNullable: true}', () => { const c = new FormControl<string>(''); { type ValueType = string | null; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = string | null; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.setValue(null); c.setValue(''); c.patchValue(null); c.patchValue(''); c.reset(); c.reset(''); }); it('should allow deprecated option {initialValueIsDefault: true}', () => { const c = new FormControl<string>('', {initialValueIsDefault: true}); { type ValueType = string; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = string; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.setValue(''); c.reset(); expect(c.value).toEqual(''); }); it('should not allow assignment to an incompatible control', () => { let fcs = new FormControl('bob'); let fcn = new FormControl(42); // @ts-expect-error fcs = fcn; // @ts-expect-error fcn = fcs; }); it('is assignable to AbstractControl', () => { let ac: AbstractControl<boolean>; ac = new FormControl(true, {nonNullable: true}); }); it('is assignable to UntypedFormControl', () => { const c = new FormControl<string>(''); let ufc: UntypedFormControl; ufc = c; }); });
{ "end_byte": 4423, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts" }
angular/packages/forms/test/typed_integration_spec.ts_4427_12204
describe('FormGroup', () => { it('supports inferred groups', () => { const c = new FormGroup({ c: new FormControl('', {nonNullable: true}), d: new FormControl(0, {nonNullable: true}), }); { type ValueType = Partial<{c: string; d: number}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {c: string; d: number}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl('c', new FormControl('', {nonNullable: true})); c.addControl('c', new FormControl('', {nonNullable: true})); c.setControl('c', new FormControl('', {nonNullable: true})); c.contains('c'); c.contains('foo'); // Contains checks always allowed c.setValue({c: '', d: 0}); c.patchValue({c: ''}); c.reset({c: '', d: 0}); }); it('supports explicit groups', () => { const c = new FormGroup<{c: FormControl<string>; d: FormControl<number>}>({ c: new FormControl('', {nonNullable: true}), d: new FormControl(0, {nonNullable: true}), }); { type ValueType = Partial<{c: string; d: number}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {c: string; d: number}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl('c', new FormControl('', {nonNullable: true})); c.addControl('c', new FormControl('', {nonNullable: true})); c.setControl('c', new FormControl('', {nonNullable: true})); c.contains('c'); c.setValue({c: '', d: 0}); c.patchValue({c: ''}); c.reset({c: '', d: 0}); }); it('supports explicit groups with boolean types', () => { const c0 = new FormGroup({a: new FormControl(true, {nonNullable: true})}); const c1: AbstractControl<{a?: boolean}, {a: boolean}> = new FormGroup({ a: new FormControl(true, {nonNullable: true}), }); // const c2: FormGroup<{a: FormControl<boolean>}> = // new FormGroup({a: new FormControl(true, {nonNullable: true})}); }); it('supports empty groups', () => { let c = new FormGroup({}); let ca: FormGroup<any> = c; }); it('supports groups with nullable controls', () => { const c = new FormGroup({ c: new FormControl<string | null>(''), d: new FormControl('', {nonNullable: true}), }); { type ValueType = Partial<{c: string | null; d: string}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {c: string | null; d: string}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl('c', new FormControl<string | null>(null)); c.addControl('c', new FormControl<string | null>(null)); c.setControl('c', new FormControl<string | null>(null)); c.contains('c'); c.setValue({c: '', d: ''}); c.setValue({c: null, d: ''}); c.patchValue({}); c.reset({}); c.reset({d: ''}); c.reset({c: ''}); c.reset({c: '', d: ''}); }); it('supports groups with the default type', () => { let c: FormGroup; let c2 = new FormGroup({c: new FormControl(''), d: new FormControl('', {nonNullable: true})}); c = c2; expect(c.value.d).toBe(''); c.value; c.reset(); c.reset({c: ''}); c.reset({c: '', d: ''}); c.reset({c: '', d: ''}, {}); c.setValue({c: '', d: ''}); c.setValue({c: 99, d: 42}); c.setControl('c', new FormControl(0)); c.setControl('notpresent', new FormControl(0)); c.removeControl('c'); c.controls['d'].valueChanges.subscribe(() => {}); }); it('supports groups with explicit named interface types', () => { interface Cat { lives: number; } interface CatControls { lives: FormControl<number>; } const c = new FormGroup<CatControls>({lives: new FormControl(9, {nonNullable: true})}); { type ValueType = Partial<Cat>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = Cat; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl('lives', new FormControl(0, {nonNullable: true})); c.addControl('lives', new FormControl(0, {nonNullable: true})); c.setControl('lives', new FormControl(0, {nonNullable: true})); c.contains('lives'); c.setValue({lives: 0}); c.patchValue({}); c.reset({lives: 0}); }); it('supports groups with nested explicit named interface types', () => { interface CatInterface { name: string; lives: number; } interface CatControlsInterface { name: FormControl<string>; lives: FormControl<number>; } interface LitterInterface { brother: CatInterface; sister: CatInterface; } interface LitterControlsInterface { brother: FormGroup<CatControlsInterface>; sister: FormGroup<CatControlsInterface>; } const bro = new FormGroup<CatControlsInterface>({ name: new FormControl('bob', {nonNullable: true}), lives: new FormControl(9, {nonNullable: true}), }); const sis = new FormGroup<CatControlsInterface>({ name: new FormControl('lucy', {nonNullable: true}), lives: new FormControl(9, {nonNullable: true}), }); const litter = new FormGroup<LitterControlsInterface>({ brother: bro, sister: sis, }); { type ValueType = Partial<{brother: Partial<CatInterface>; sister: Partial<CatInterface>}>; let t: ValueType = litter.value; let t1 = litter.value; t1 = null as unknown as ValueType; } { type RawValueType = LitterInterface; let t: RawValueType = litter.getRawValue(); let t1 = litter.getRawValue(); t1 = null as unknown as RawValueType; } litter.patchValue({brother: {name: 'jim'}}); litter.controls.brother.setValue({name: 'jerry', lives: 1}); }); it('supports nested inferred groups', () => { const c = new FormGroup({ innerGroup: new FormGroup({innerControl: new FormControl('', {nonNullable: true})}), }); { type ValueType = Partial<{innerGroup: Partial<{innerControl: string}>}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {innerGroup: {innerControl: string}}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl( 'innerGroup', new FormGroup({innerControl: new FormControl('', {nonNullable: true})}), ); c.addControl( 'innerGroup', new FormGroup({innerControl: new FormControl('', {nonNullable: true})}), ); c.setControl( 'innerGroup', new FormGroup({innerControl: new FormControl('', {nonNullable: true})}), ); c.contains('innerGroup'); c.setValue({innerGroup: {innerControl: ''}}); c.patchValue({}); c.reset({innerGroup: {innerControl: ''}}); });
{ "end_byte": 12204, "start_byte": 4427, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts" }
angular/packages/forms/test/typed_integration_spec.ts_12210_20436
it('supports nested explicit groups', () => { const ig = new FormControl('', {nonNullable: true}); const og = new FormGroup({innerControl: ig}); const c = new FormGroup<{innerGroup: FormGroup<{innerControl: FormControl<string>}>}>({ innerGroup: og, }); { type ValueType = Partial<{innerGroup: Partial<{innerControl: string}>}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {innerGroup: {innerControl: string}}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } // Methods are tested in the inferred case }); it('supports groups with a single optional control', () => { const c = new FormGroup<{c?: FormControl<string>}>({ c: new FormControl<string>('', {nonNullable: true}), }); { type ValueType = Partial<{c?: string}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {c?: string}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } }); it('supports groups with mixed optional controls', () => { const c = new FormGroup<{c?: FormControl<string>; d: FormControl<string>}>({ c: new FormControl<string>('', {nonNullable: true}), d: new FormControl('', {nonNullable: true}), }); { type ValueType = Partial<{c?: string; d: string}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {c?: string; d: string}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl('c', new FormControl<string>('', {nonNullable: true})); c.addControl('c', new FormControl<string>('', {nonNullable: true})); c.removeControl('c'); c.setControl('c', new FormControl<string>('', {nonNullable: true})); c.contains('c'); c.setValue({c: '', d: ''}); c.patchValue({}); c.reset({}); c.reset({c: ''}); c.reset({d: ''}); c.reset({c: '', d: ''}); // @ts-expect-error c.removeControl('d'); // This is not allowed }); it('supports nested groups with optional controls', () => { type t = FormGroup<{meal: FormGroup<{dessert?: FormControl<string>}>}>; const menu = new FormGroup<{meal: FormGroup<{dessert?: FormControl<string>}>}>({ meal: new FormGroup({}), }); { type ValueType = Partial<{meal: Partial<{dessert?: string}>}>; let t: ValueType = menu.value; let t1 = menu.value; t1 = null as unknown as ValueType; } { type RawValueType = {meal: {dessert?: string}}; let t: RawValueType = menu.getRawValue(); let t1 = menu.getRawValue(); t1 = null as unknown as RawValueType; } menu.controls.meal.removeControl('dessert'); }); it('supports groups with inferred nested arrays', () => { const arr = new FormArray([new FormControl('', {nonNullable: true})]); const c = new FormGroup({a: arr}); { type ValueType = Partial<{a: Array<string>}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {a: Array<string>}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl( 'a', new FormArray([ new FormControl('', {nonNullable: true}), new FormControl('', {nonNullable: true}), ]), ); c.registerControl('a', new FormArray([new FormControl('', {nonNullable: true})])); // @ts-expect-error c.registerControl('a', new FormArray([])); c.registerControl('a', new FormArray<FormControl<string>>([])); c.addControl( 'a', new FormArray([ new FormControl('', {nonNullable: true}), new FormControl('', {nonNullable: true}), ]), ); c.addControl('a', new FormArray([new FormControl('', {nonNullable: true})])); // @ts-expect-error c.addControl('a', new FormArray([])); c.setControl( 'a', new FormArray([ new FormControl('', {nonNullable: true}), new FormControl('', {nonNullable: true}), ]), ); c.setControl('a', new FormArray([new FormControl('', {nonNullable: true})])); // @ts-expect-error c.setControl('a', new FormArray([])); c.contains('a'); c.patchValue({a: ['', '']}); c.patchValue({a: ['']}); c.patchValue({a: []}); c.patchValue({}); c.reset({a: ['', '']}); c.reset({a: ['']}); c.reset({a: []}); }); it('supports groups with explicit nested arrays', () => { const arr = new FormArray<FormControl<string>>([new FormControl('', {nonNullable: true})]); const c = new FormGroup<{a: FormArray<FormControl<string>>}>({a: arr}); { type ValueType = Partial<{a: Array<string>}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {a: Array<string>}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } // Methods are tested in the inferred case }); it('supports groups with an index type', () => { // This test is required for the default case, which relies on an index type with values // AbstractControl<any>. interface AddressBookValues { returnIfFound: string; [name: string]: string; } interface AddressBookControls { returnIfFound: FormControl<string>; [name: string]: FormControl<string>; } const c = new FormGroup<AddressBookControls>({ returnIfFound: new FormControl('1234 Geary, San Francisco', {nonNullable: true}), alex: new FormControl('999 Valencia, San Francisco', {nonNullable: true}), andrew: new FormControl('100 Lombard, San Francisco', {nonNullable: true}), }); { type ValueType = Partial<AddressBookValues>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = AddressBookValues; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } // Named fields. c.registerControl( 'returnIfFound', new FormControl('200 Ellis, San Francisco', {nonNullable: true}), ); c.addControl( 'returnIfFound', new FormControl('200 Ellis, San Francisco', {nonNullable: true}), ); c.setControl( 'returnIfFound', new FormControl('200 Ellis, San Francisco', {nonNullable: true}), ); // c.removeControl('returnIfFound'); // Not allowed c.contains('returnIfFound'); c.setValue({returnIfFound: '200 Ellis, San Francisco', alex: '1 Main', andrew: '2 Main'}); c.patchValue({}); c.reset({returnIfFound: '200 Ellis, San Francisco'}); // Indexed fields. c.registerControl('igor', new FormControl('300 Page, San Francisco', {nonNullable: true})); c.addControl('igor', new FormControl('300 Page, San Francisco', {nonNullable: true})); c.setControl('igor', new FormControl('300 Page, San Francisco', {nonNullable: true})); c.contains('igor'); c.setValue({ returnIfFound: '200 Ellis, San Francisco', igor: '300 Page, San Francisco', alex: '1 Main', andrew: '2 Page', }); c.patchValue({}); c.reset({returnIfFound: '200 Ellis, San Francisco', igor: '300 Page, San Francisco'}); // @ts-expect-error c.removeControl('igor'); });
{ "end_byte": 20436, "start_byte": 12210, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts" }
angular/packages/forms/test/typed_integration_spec.ts_20442_24401
it('should have strongly-typed get', () => { const c = new FormGroup({ venue: new FormGroup({ address: new FormControl('2200 Bryant', {nonNullable: true}), date: new FormGroup({ day: new FormControl(21, {nonNullable: true}), month: new FormControl('March', {nonNullable: true}), }), }), }); const rv = c.getRawValue(); { type ValueType = {day: number; month: string}; let t: ValueType = c.get('venue.date')!.value; let t1 = c.get('venue.date')!.value; t1 = null as unknown as ValueType; } { type ValueType = string; let t: ValueType = c.get('venue.date.month')!.value; let t1 = c.get('venue.date.month')!.value; t1 = null as unknown as ValueType; } { type ValueType = string; let t: ValueType = c.get(['venue', 'date', 'month'] as const)!.value; let t1 = c.get(['venue', 'date', 'month'] as const)!.value; t1 = null as unknown as ValueType; } { // .get(...) should be `never`, but we use `?` to coerce to undefined so the test passes at // runtime. type ValueType = never | undefined; let t: ValueType = c.get('foobar')?.value; let t1 = c.get('foobar')?.value; t1 = null as unknown as ValueType; } }); it('is assignable to AbstractControl', () => { let ac: AbstractControl<{a?: boolean}>; ac = new FormGroup({a: new FormControl(true, {nonNullable: true})}); }); it('is assignable to UntypedFormGroup', () => { let ufg: UntypedFormGroup; const fg = new FormGroup({name: new FormControl('bob')}); ufg = fg; }); it('is assignable to UntypedFormGroup in a complex case', () => { interface Cat { name: FormControl<string | null>; lives?: FormControl<number>; } let ufg: UntypedFormGroup; const fg = new FormGroup({ myCats: new FormArray([new FormGroup<Cat>({name: new FormControl('bob')})]), }); ufg = fg; }); }); describe('FormRecord', () => { it('supports inferred records', () => { let c = new FormRecord({a: new FormControl(42, {nonNullable: true})}); { type ValueType = Partial<{[key: string]: number}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {[key: string]: number}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl('c', new FormControl(42, {nonNullable: true})); c.addControl('c', new FormControl(42, {nonNullable: true})); c.setControl('c', new FormControl(42, {nonNullable: true})); c.removeControl('c'); c.removeControl('missing'); c.contains('c'); c.contains('foo'); c.setValue({a: 42}); c.patchValue({c: 42}); c.reset({c: 42, d: 0}); }); it('supports explicit records', () => { let c = new FormRecord<FormControl<number>>({a: new FormControl(42, {nonNullable: true})}); { type ValueType = Partial<{[key: string]: number}>; let t: ValueType = c.value; let t1 = c.value; t1 = null as unknown as ValueType; } { type RawValueType = {[key: string]: number}; let t: RawValueType = c.getRawValue(); let t1 = c.getRawValue(); t1 = null as unknown as RawValueType; } c.registerControl('c', new FormControl(42, {nonNullable: true})); c.addControl('c', new FormControl(42, {nonNullable: true})); c.setControl('c', new FormControl(42, {nonNullable: true})); c.contains('c'); c.contains('foo'); c.setValue({a: 42, c: 0}); c.patchValue({c: 42}); c.reset({c: 42, d: 0}); c.removeControl('c'); }); });
{ "end_byte": 24401, "start_byte": 20442, "url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts" }