_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/core/test/acceptance/host_directives_spec.ts_61788_64341
it('should not expose an input under its host directive alias if a host directive is not applied', () => { const logs: string[] = []; @Directive({selector: '[host-dir]', standalone: true}) class HostDir implements OnChanges { @Input('colorAlias') color?: string; ngOnChanges(changes: SimpleChanges) { logs.push(changes['color'].currentValue); } } @Directive({ selector: '[dir]', standalone: true, hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColor']}], }) class Dir {} @Component({ standalone: true, imports: [Dir, HostDir], // Note that `[dir]` doesn't match on the `button` on purpose. // The wrong behavior would be if the `buttonColor` binding worked on `host-dir`. template: ` <span dir [buttonColor]="spanValue"></span> <button host-dir [buttonColor]="buttonValue"></button> `, }) class App { spanValue = 'spanValue'; buttonValue = 'buttonValue'; } TestBed.configureTestingModule({errorOnUnknownProperties: true}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError(/Can't bind to 'buttonColor' since it isn't a known property of 'button'/); // The input on the button instance should not have been written to. expect(logs).toEqual(['spanValue']); }); it('should set the input of an inherited host directive that has been exposed', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ hostDirectives: [{directive: HostDir, inputs: ['color']}], standalone: false, }) class Parent {} @Directive({ selector: '[dir]', standalone: false, }) class Dir extends Parent {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('red'); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('green'); }); });
{ "end_byte": 64341, "start_byte": 61788, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_64345_72157
describe('ngOnChanges', () => { it('should invoke ngOnChanges when an input is set on a host directive', () => { let firstDirChangeEvent: SimpleChanges | undefined; let secondDirChangeEvent: SimpleChanges | undefined; @Directive({standalone: true}) class FirstHostDir implements OnChanges { @Input() color?: string; ngOnChanges(changes: SimpleChanges) { firstDirChangeEvent = changes; } } @Directive({standalone: true}) class SecondHostDir implements OnChanges { @Input() color?: string; ngOnChanges(changes: SimpleChanges) { secondDirChangeEvent = changes; } } @Directive({ selector: '[dir]', hostDirectives: [ {directive: FirstHostDir, inputs: ['color']}, {directive: SecondHostDir, inputs: ['color']}, ], standalone: false, }) class Dir {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(firstDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(firstDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); }); it('should invoke ngOnChanges when an aliased property is set on a host directive', () => { let firstDirChangeEvent: SimpleChanges | undefined; let secondDirChangeEvent: SimpleChanges | undefined; @Directive({standalone: true}) class FirstHostDir implements OnChanges { @Input('firstAlias') color?: string; ngOnChanges(changes: SimpleChanges) { firstDirChangeEvent = changes; } } @Directive({standalone: true}) class SecondHostDir implements OnChanges { @Input('secondAlias') color?: string; ngOnChanges(changes: SimpleChanges) { secondDirChangeEvent = changes; } } @Directive({ selector: '[dir]', hostDirectives: [ {directive: FirstHostDir, inputs: ['firstAlias: buttonColor']}, {directive: SecondHostDir, inputs: ['secondAlias: buttonColor']}, ], standalone: false, }) class Dir {} @Component({ template: '<button dir [buttonColor]="color"></button>', standalone: false, }) class App { color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(firstDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(firstDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); }); it('should only invoke ngOnChanges on the directives that have exposed an input', () => { let firstDirChangeEvent: SimpleChanges | undefined; let secondDirChangeEvent: SimpleChanges | undefined; @Directive({standalone: true}) class FirstHostDir implements OnChanges { @Input() color?: string; ngOnChanges(changes: SimpleChanges) { firstDirChangeEvent = changes; } } @Directive({standalone: true}) class SecondHostDir implements OnChanges { @Input() color?: string; ngOnChanges(changes: SimpleChanges) { secondDirChangeEvent = changes; } } @Directive({ selector: '[dir]', hostDirectives: [FirstHostDir, {directive: SecondHostDir, inputs: ['color']}], standalone: false, }) class Dir {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(firstDirChangeEvent).toBe(undefined); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(firstDirChangeEvent).toBe(undefined); expect(secondDirChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: false, previousValue: 'red', currentValue: 'green', }), }), ); }); it('should invoke ngOnChanges when a static aliased host directive input is set', () => { let latestChangeEvent: SimpleChanges | undefined; @Directive({standalone: true}) class HostDir implements OnChanges { @Input('colorAlias') color?: string; ngOnChanges(changes: SimpleChanges) { latestChangeEvent = changes; } } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColor']}], standalone: false, }) class Dir {} @Component({ template: '<button dir buttonColor="red"></button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(latestChangeEvent).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ firstChange: true, previousValue: undefined, currentValue: 'red', }), }), ); }); });
{ "end_byte": 72157, "start_byte": 64345, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_72161_76434
describe('debugging and testing utilities', () => { it('should be able to retrieve host directives using ng.getDirectives', () => { let hostDirInstance!: HostDir; let otherHostDirInstance!: OtherHostDir; let plainDirInstance!: PlainDir; @Directive({standalone: true}) class HostDir { constructor() { hostDirInstance = this; } } @Directive({standalone: true}) class OtherHostDir { constructor() { otherHostDirInstance = this; } } @Directive({ selector: '[plain-dir]', standalone: false, }) class PlainDir { constructor() { plainDirInstance = this; } } @Component({ selector: 'comp', template: '', hostDirectives: [HostDir, OtherHostDir], standalone: false, }) class Comp {} @Component({ template: '<comp plain-dir></comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Comp, PlainDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const componentHost = fixture.nativeElement.querySelector('comp'); expect(hostDirInstance instanceof HostDir).toBe(true); expect(otherHostDirInstance instanceof OtherHostDir).toBe(true); expect(plainDirInstance instanceof PlainDir).toBe(true); expect(getDirectives(componentHost)).toEqual([ hostDirInstance, otherHostDirInstance, plainDirInstance, ]); }); it('should be able to retrieve components that have host directives using ng.getComponent', () => { let compInstance!: Comp; @Directive({standalone: true}) class HostDir {} @Component({ selector: 'comp', template: '', hostDirectives: [HostDir], standalone: false, }) class Comp { constructor() { compInstance = this; } } @Component({ template: '<comp></comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Comp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const componentHost = fixture.nativeElement.querySelector('comp'); expect(compInstance instanceof Comp).toBe(true); expect(getComponent(componentHost)).toBe(compInstance); }); it('should be able to retrieve components that have host directives using DebugNode.componentInstance', () => { let compInstance!: Comp; @Directive({standalone: true}) class HostDir {} @Component({ selector: 'comp', template: '', hostDirectives: [HostDir], standalone: false, }) class Comp { constructor() { compInstance = this; } } @Component({ template: '<comp></comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Comp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const node = fixture.debugElement.query(By.css('comp')); expect(compInstance instanceof Comp).toBe(true); expect(node.componentInstance).toBe(compInstance); }); it('should be able to query by a host directive', () => { @Directive({standalone: true}) class HostDir {} @Component({ selector: 'comp', template: '', hostDirectives: [HostDir], standalone: false, }) class Comp { constructor(public elementRef: ElementRef<HTMLElement>) {} } @Component({ template: '<comp></comp>', standalone: false, }) class App { @ViewChild(Comp) compInstance!: Comp; } TestBed.configureTestingModule({declarations: [App, Comp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const expected = fixture.componentInstance.compInstance.elementRef.nativeElement; const result = fixture.debugElement.query(By.directive(HostDir)).nativeElement; expect(result).toBe(expected); }); });
{ "end_byte": 76434, "start_byte": 72161, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_76438_83437
describe('root component with host directives', () => { function createRootComponent<T>(componentType: Type<T>) { @Component({ template: '<ng-container #insertionPoint></ng-container>', standalone: false, }) class App { @ViewChild('insertionPoint', {read: ViewContainerRef}) insertionPoint!: ViewContainerRef; } TestBed.configureTestingModule({ declarations: [App, componentType], errorOnUnknownProperties: true, }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const ref = fixture.componentInstance.insertionPoint.createComponent(componentType); return {ref, fixture}; } it('should apply a basic host directive to the root component', () => { const logs: string[] = []; @Directive({ standalone: true, host: {'host-dir-attr': '', 'class': 'host-dir', 'style': 'height: 50px'}, }) class HostDir { constructor() { logs.push('HostDir'); } } @Component({ selector: 'host', host: {'host-attr': '', 'class': 'dir', 'style': 'width: 50px'}, hostDirectives: [HostDir], template: '', standalone: false, }) class HostComp { constructor() { logs.push('HostComp'); } } const {fixture} = createRootComponent(HostComp); expect(logs).toEqual(['HostDir', 'HostComp']); expect(fixture.nativeElement.innerHTML).toContain( '<host host-dir-attr="" host-attr="" class="host-dir dir" ' + 'style="height: 50px; width: 50px;"></host>', ); }); it('should invoke lifecycle hooks on host directives applied to a root component', () => { const logs: string[] = []; @Directive({standalone: true}) class HostDir implements OnInit, AfterViewInit, AfterViewChecked { ngOnInit() { logs.push('HostDir - ngOnInit'); } ngAfterViewInit() { logs.push('HostDir - ngAfterViewInit'); } ngAfterViewChecked() { logs.push('HostDir - ngAfterViewChecked'); } } @Directive({standalone: true}) class OtherHostDir implements OnInit, AfterViewInit, AfterViewChecked { ngOnInit() { logs.push('OtherHostDir - ngOnInit'); } ngAfterViewInit() { logs.push('OtherHostDir - ngAfterViewInit'); } ngAfterViewChecked() { logs.push('OtherHostDir - ngAfterViewChecked'); } } @Component({ template: '', hostDirectives: [HostDir, OtherHostDir], standalone: false, }) class HostComp implements OnInit, AfterViewInit, AfterViewChecked { ngOnInit() { logs.push('HostComp - ngOnInit'); } ngAfterViewInit() { logs.push('HostComp - ngAfterViewInit'); } ngAfterViewChecked() { logs.push('HostComp - ngAfterViewChecked'); } } const {fixture} = createRootComponent(HostComp); fixture.detectChanges(); expect(logs).toEqual([ 'HostDir - ngOnInit', 'OtherHostDir - ngOnInit', 'HostComp - ngOnInit', 'HostDir - ngAfterViewInit', 'HostDir - ngAfterViewChecked', 'OtherHostDir - ngAfterViewInit', 'OtherHostDir - ngAfterViewChecked', 'HostComp - ngAfterViewInit', 'HostComp - ngAfterViewChecked', ]); }); describe('host bindings', () => { it('should support host attribute bindings coming from the host directives', () => { @Directive({ standalone: true, host: { '[attr.host-dir-only]': 'value', '[attr.shadowed-attr]': 'value', }, }) class HostDir { value = 'host-dir'; } @Directive({ standalone: true, host: { '[attr.other-host-dir-only]': 'value', '[attr.shadowed-attr]': 'value', }, }) class OtherHostDir { value = 'other-host-dir'; } @Component({ selector: 'host-comp', host: { '[attr.shadowed-attr]': 'value', }, hostDirectives: [HostDir, OtherHostDir], standalone: false, }) class HostComp { value = 'host'; hostDir = inject(HostDir); otherHostDir = inject(OtherHostDir); } const {fixture, ref} = createRootComponent(HostComp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toContain( '<host-comp host-dir-only="host-dir" shadowed-attr="host" ' + 'other-host-dir-only="other-host-dir"></host-comp>', ); ref.instance.hostDir.value = 'host-dir-changed'; ref.instance.otherHostDir.value = 'other-host-dir-changed'; ref.instance.value = 'host-changed'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toContain( '<host-comp host-dir-only="host-dir-changed" shadowed-attr="host-changed" ' + 'other-host-dir-only="other-host-dir-changed"></host-comp>', ); }); it('should support host event bindings coming from the host directives', () => { const logs: string[] = []; @Directive({standalone: true, host: {'(click)': 'handleClick()'}}) class HostDir { handleClick() { logs.push('HostDir'); } } @Directive({standalone: true, host: {'(click)': 'handleClick()'}}) class OtherHostDir { handleClick() { logs.push('OtherHostDir'); } } @Component({ selector: 'host-comp', host: {'(click)': 'handleClick()'}, hostDirectives: [HostDir, OtherHostDir], standalone: false, }) class HostComp { handleClick() { logs.push('HostComp'); } } const {fixture, ref} = createRootComponent(HostComp); ref.location.nativeElement.click(); fixture.detectChanges(); expect(logs).toEqual(['HostDir', 'OtherHostDir', 'HostComp']); }); it('should have the host bindings of the root component take precedence over the ones from the host directives', () => { @Directive({standalone: true, host: {'id': 'host-dir'}}) class HostDir {} @Directive({standalone: true, host: {'id': 'other-host-dir'}}) class OtherHostDir {} @Component({ template: '', host: {'id': 'host'}, hostDirectives: [HostDir, OtherHostDir], standalone: false, }) class HostComp {} const {ref, fixture} = createRootComponent(HostComp); fixture.detectChanges(); expect(ref.location.nativeElement.getAttribute('id')).toBe('host'); }); });
{ "end_byte": 83437, "start_byte": 76438, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_83443_87474
describe('dependency injection', () => { it('should allow the host directive to inject the root component', () => { let hostDirInstance!: HostDir; @Directive({standalone: true}) class HostDir { host = inject(HostComp); constructor() { hostDirInstance = this; } } @Component({ hostDirectives: [HostDir], template: '', standalone: false, }) class HostComp {} const {ref} = createRootComponent(HostComp); expect(hostDirInstance instanceof HostDir).toBe(true); expect(hostDirInstance.host).toBe(ref.instance); }); it('should allow the root component to inject the host directive', () => { let hostDirInstance!: HostDir; @Directive({standalone: true}) class HostDir { constructor() { hostDirInstance = this; } } @Component({ hostDirectives: [HostDir], template: '', standalone: false, }) class HostComp { hostDir = inject(HostDir); } const {ref} = createRootComponent(HostComp); expect(hostDirInstance instanceof HostDir).toBe(true); expect(ref.instance.hostDir).toBe(hostDirInstance); }); it('should give precedence to the DI tokens from the root component over the host directive tokens', () => { const token = new InjectionToken<string>('token'); let hostInstance!: HostComp; let firstHostDirInstance!: FirstHostDir; let secondHostDirInstance!: SecondHostDir; @Directive({standalone: true, providers: [{provide: token, useValue: 'SecondDir'}]}) class SecondHostDir { tokenValue = inject(token); constructor() { secondHostDirInstance = this; } } @Directive({ standalone: true, hostDirectives: [SecondHostDir], providers: [{provide: token, useValue: 'FirstDir'}], }) class FirstHostDir { tokenValue = inject(token); constructor() { firstHostDirInstance = this; } } @Component({ template: '', hostDirectives: [FirstHostDir], providers: [{provide: token, useValue: 'HostDir'}], standalone: false, }) class HostComp { tokenValue = inject(token); constructor() { hostInstance = this; } } createRootComponent(HostComp); expect(hostInstance instanceof HostComp).toBe(true); expect(firstHostDirInstance instanceof FirstHostDir).toBe(true); expect(secondHostDirInstance instanceof SecondHostDir).toBe(true); expect(hostInstance.tokenValue).toBe('HostDir'); expect(firstHostDirInstance.tokenValue).toBe('HostDir'); expect(secondHostDirInstance.tokenValue).toBe('HostDir'); }); it('should allow the root component to inject tokens from the host directives', () => { const firstToken = new InjectionToken<string>('firstToken'); const secondToken = new InjectionToken<string>('secondToken'); @Directive({standalone: true, providers: [{provide: secondToken, useValue: 'SecondDir'}]}) class SecondHostDir {} @Directive({ standalone: true, hostDirectives: [SecondHostDir], providers: [{provide: firstToken, useValue: 'FirstDir'}], }) class FirstHostDir {} @Component({ template: '', hostDirectives: [FirstHostDir], standalone: false, }) class HostComp { firstTokenValue = inject(firstToken); secondTokenValue = inject(secondToken); } const {ref} = createRootComponent(HostComp); expect(ref.instance.firstTokenValue).toBe('FirstDir'); expect(ref.instance.secondTokenValue).toBe('SecondDir'); }); });
{ "end_byte": 87474, "start_byte": 83443, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_87480_94213
describe('inputs', () => { it('should set inputs on root component and all host directive instances using `setInput`', () => { let hostDirInstance!: HostDir; let otherHostDirInstance!: OtherHostDir; @Directive({standalone: true}) class HostDir { @Input() color?: string; constructor() { hostDirInstance = this; } } @Directive({standalone: true}) class OtherHostDir { @Input() color?: string; constructor() { otherHostDirInstance = this; } } @Component({ selector: 'host-comp', hostDirectives: [ { directive: HostDir, inputs: ['color'], }, { directive: OtherHostDir, inputs: ['color'], }, ], standalone: false, }) class HostComp { @Input() color?: string; } const {fixture, ref} = createRootComponent(HostComp); fixture.detectChanges(); expect(hostDirInstance.color).toBe(undefined); expect(otherHostDirInstance.color).toBe(undefined); expect(ref.instance.color).toBe(undefined); ref.setInput('color', 'green'); expect(hostDirInstance.color).toBe('green'); expect(otherHostDirInstance.color).toBe('green'); expect(ref.instance.color).toBe('green'); }); it('should set inputs that only exist on a host directive when using `setInput`', () => { let hostDirInstance!: HostDir; @Directive({standalone: true}) class HostDir { @Input() color?: string; constructor() { hostDirInstance = this; } } @Component({ selector: 'host-comp', hostDirectives: [ { directive: HostDir, inputs: ['color'], }, ], standalone: false, }) class HostComp { color?: string; // Note: intentionally not marked as @Input. } const {ref} = createRootComponent(HostComp); expect(hostDirInstance.color).toBe(undefined); expect(ref.instance.color).toBe(undefined); ref.setInput('color', 'color'); expect(hostDirInstance.color).toBe('color'); expect(ref.instance.color).toBe(undefined); }); it('should set inputs that only exist on the root component when using `setInput`', () => { let hostDirInstance!: HostDir; @Directive({standalone: true}) class HostDir { @Input() color?: string; constructor() { hostDirInstance = this; } } @Component({ selector: 'host-comp', hostDirectives: [HostDir], standalone: false, }) class HostComp { @Input() color?: string; } const {ref, fixture} = createRootComponent(HostComp); fixture.detectChanges(); expect(hostDirInstance.color).toBe(undefined); expect(ref.instance.color).toBe(undefined); ref.setInput('color', 'green'); expect(hostDirInstance.color).toBe(undefined); expect(ref.instance.color).toBe('green'); }); it('should use the input name alias in `setInput`', () => { let hostDirInstance!: HostDir; @Directive({standalone: true}) class HostDir { @Input('alias') color?: string; constructor() { hostDirInstance = this; } } @Component({ selector: 'host-comp', hostDirectives: [ { directive: HostDir, inputs: ['alias: customAlias'], }, ], standalone: false, }) class HostComp {} const {ref, fixture} = createRootComponent(HostComp); fixture.detectChanges(); expect(hostDirInstance.color).toBe(undefined); // Check that the old alias or the original name aren't available first. expect(() => ref.setInput('color', 'hello')).toThrowError( /NG0303: Can't set value of the 'color' input/, ); expect(() => ref.setInput('alias', 'hello')).toThrowError( /NG0303: Can't set value of the 'alias' input/, ); expect(hostDirInstance.color).toBe(undefined); // Check the alias. ref.setInput('customAlias', 'hello'); expect(hostDirInstance.color).toBe('hello'); }); it('should invoke ngOnChanges when setting host directive inputs using setInput', () => { let latestChanges: SimpleChanges | undefined; @Directive({standalone: true}) class HostDir implements OnChanges { @Input('alias') color?: string; ngOnChanges(changes: SimpleChanges) { latestChanges = changes; } } @Component({ selector: 'host-comp', hostDirectives: [{directive: HostDir, inputs: ['alias: customAlias']}], standalone: false, }) class HostComp {} const {ref, fixture} = createRootComponent(HostComp); expect(latestChanges).toBe(undefined); ref.setInput('customAlias', 'red'); fixture.detectChanges(); expect(latestChanges).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ previousValue: undefined, currentValue: 'red', firstChange: true, }), }), ); ref.setInput('customAlias', 'green'); fixture.detectChanges(); expect(latestChanges).toEqual( jasmine.objectContaining({ color: jasmine.objectContaining({ previousValue: 'red', currentValue: 'green', firstChange: false, }), }), ); }); }); it('should throw an error if a host directive is applied multiple times to a root component', () => { @Directive({standalone: true}) class DuplicateHostDir {} @Directive({standalone: true, hostDirectives: [DuplicateHostDir]}) class HostDir {} @Directive({standalone: true, hostDirectives: [HostDir, DuplicateHostDir]}) class Dir {} @Component({ hostDirectives: [Dir], standalone: false, }) class HostComp {} expect(() => createRootComponent(HostComp)).toThrowError( 'NG0309: Directive DuplicateHostDir matches multiple times on the same element. Directives can only match an element once.', ); }); });
{ "end_byte": 94213, "start_byte": 87480, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_94217_102839
describe('invalid usage validations', () => { it('should throw an error if the metadata of a host directive cannot be resolved', () => { class HostDir {} @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0307: Could not resolve metadata for host directive HostDir. ' + 'Make sure that the HostDir class is annotated with an @Directive decorator.', ); }); it('should throw an error if a host directive is not standalone', () => { @Directive({standalone: false}) class HostDir {} @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0308: Host directive HostDir must be standalone.', ); }); it('should throw an error if a host directive matches multiple times in a template', () => { @Directive({standalone: true, selector: '[dir]'}) class HostDir {} @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: true, }) class Dir {} @Component({template: '<div dir></div>', standalone: true, imports: [HostDir, Dir]}) class App {} expect(() => TestBed.createComponent(App)).toThrowError( 'NG0309: Directive HostDir matches multiple times on the same element. Directives can only match an element once.', ); }); it('should throw an error if a host directive matches multiple times on a component', () => { @Directive({standalone: true, selector: '[dir]'}) class HostDir {} @Component({ selector: 'comp', hostDirectives: [HostDir], standalone: true, template: '', }) class Comp {} const baseAppMetadata = { template: '<comp dir></comp>', standalone: true, }; const expectedError = 'NG0309: Directive HostDir matches multiple times on the same element. Directives can only match an element once.'; // Note: the definition order in `imports` seems to affect the // directive matching order so we test both scenarios. expect(() => { @Component({ ...baseAppMetadata, imports: [Comp, HostDir], }) class App {} TestBed.createComponent(App); }).toThrowError(expectedError); expect(() => { @Component({ ...baseAppMetadata, imports: [HostDir, Comp], }) class App {} TestBed.createComponent(App); }).toThrowError(expectedError); }); it('should throw an error if a host directive appears multiple times in a chain', () => { @Directive({standalone: true}) class DuplicateHostDir {} @Directive({standalone: true, hostDirectives: [DuplicateHostDir]}) class HostDir {} @Directive({ selector: '[dir]', hostDirectives: [HostDir, DuplicateHostDir], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0309: Directive DuplicateHostDir matches multiple times on the same element. Directives can only match an element once.', ); }); it('should throw an error if a host directive is a component', () => { @Component({standalone: true, template: '', selector: 'host-comp'}) class HostComp {} @Directive({ selector: '[dir]', hostDirectives: [HostComp], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0310: Host directive HostComp cannot be a component.', ); }); it('should throw an error if a host directive output does not exist', () => { @Directive({standalone: true}) class HostDir { @Output() foo = new EventEmitter(); } @Directive({ selector: '[dir]', hostDirectives: [ { directive: HostDir, outputs: ['doesNotExist'], }, ], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0311: Directive HostDir does not have an output with a public name of doesNotExist.', ); }); it('should throw an error if a host directive output alias does not exist', () => { @Directive({standalone: true}) class HostDir { @Output('alias') foo = new EventEmitter(); } @Directive({ selector: '[dir]', hostDirectives: [ { directive: HostDir, outputs: ['foo'], }, ], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0311: Directive HostDir does not have an output with a public name of foo.', ); }); it('should throw an error if a host directive input does not exist', () => { @Directive({standalone: true}) class HostDir { @Input() foo: any; } @Directive({ selector: '[dir]', hostDirectives: [ { directive: HostDir, inputs: ['doesNotExist'], }, ], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0311: Directive HostDir does not have an input with a public name of doesNotExist.', ); }); it('should throw an error if a host directive input alias does not exist', () => { @Directive({standalone: true}) class HostDir { @Input('alias') foo: any; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['foo']}], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0311: Directive HostDir does not have an input with a public name of foo.', ); }); it('should throw an error if a host directive tries to alias to an existing input', () => { @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Input('colorAlias') color?: string; @Input() buttonColor?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColor']}], standalone: false, }) class Dir {} @Component({ imports: [Dir, HostDir], template: '<button dir buttonColor="red"></button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError( 'NG0312: Cannot alias input colorAlias of host directive HostDir ' + 'to buttonColor, because it already has a different input with the same public name.', ); });
{ "end_byte": 102839, "start_byte": 94217, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_102845_108960
it('should throw an error if a host directive tries to alias to an existing input alias', () => { @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Input('colorAlias') color?: string; @Input('buttonColorAlias') buttonColor?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColorAlias']}], standalone: false, }) class Dir {} @Component({ imports: [Dir, HostDir], template: '<button dir buttonColorAlias="red"></button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError( 'NG0312: Cannot alias input colorAlias of host directive HostDir ' + 'to buttonColorAlias, because it already has a different input with the same public name.', ); }); it('should not throw if a host directive input aliases to the same name', () => { @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Input('color') color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color: buttonColor']}], standalone: false, }) class Dir {} @Component({ imports: [Dir, HostDir], template: '<button dir buttonColor="red"></button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).not.toThrow(); }); it('should throw an error if a host directive tries to alias to an existing output alias', () => { @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Output('clickedAlias') clicked = new EventEmitter(); @Output('tappedAlias') tapped = new EventEmitter(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['clickedAlias: tappedAlias']}], standalone: false, }) class Dir {} @Component({ imports: [Dir, HostDir], template: '<button dir (tappedAlias)="handleTap()"></button>', standalone: false, }) class App { handleTap() {} } TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError( 'NG0312: Cannot alias output clickedAlias of host directive HostDir ' + 'to tappedAlias, because it already has a different output with the same public name.', ); }); it('should not throw if a host directive output aliases to the same name', () => { @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Output('clicked') clicked = new EventEmitter(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['clicked: wasClicked']}], standalone: false, }) class Dir {} @Component({ imports: [Dir, HostDir], template: '<button dir (wasClicked)="handleClick()"></button>', standalone: false, }) class App { handleClick() {} } TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).not.toThrow(); }); it('should not throw when exposing an aliased binding', () => { @Directive({ outputs: ['opened: triggerOpened'], selector: '[trigger]', standalone: true, }) class Trigger { opened = new EventEmitter(); } @Directive({ standalone: true, selector: '[host]', hostDirectives: [{directive: Trigger, outputs: ['triggerOpened']}], }) class Host {} @Component({template: '<div host></div>', standalone: true, imports: [Host]}) class App {} expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).not.toThrow(); }); it('should not throw when exposing an inherited aliased binding', () => { @Directive({standalone: true}) abstract class Base { opened = new EventEmitter(); } @Directive({ outputs: ['opened: triggerOpened'], selector: '[trigger]', standalone: true, }) class Trigger extends Base {} @Directive({ standalone: true, selector: '[host]', hostDirectives: [{directive: Trigger, outputs: ['triggerOpened: hostOpened']}], }) class Host {} @Component({template: '<div host></div>', standalone: true, imports: [Host]}) class App {} expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).not.toThrow(); }); it('should throw an error if a duplicate directive is inherited', () => { @Directive({standalone: true}) class HostDir {} @Directive({standalone: true, hostDirectives: [HostDir]}) class Grandparent {} @Directive({standalone: true}) class Parent extends Grandparent {} @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir extends Parent {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); expect(() => TestBed.createComponent(App)).toThrowError( 'NG0309: Directive HostDir matches multiple times on the same element. Directives can only match an element once.', ); }); }); });
{ "end_byte": 108960, "start_byte": 102845, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/common_integration_spec.ts_0_6766
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, Directive} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('@angular/common integration', () => { describe('NgForOf', () => { @Directive({ selector: '[dir]', standalone: false, }) class MyDirective {} @Component({ selector: 'app-child', template: '<div dir>comp text</div>', standalone: false, }) class ChildComponent {} @Component({ selector: 'app-root', template: '', standalone: false, }) class AppComponent { items: string[] = ['first', 'second']; } beforeEach(() => { TestBed.configureTestingModule({declarations: [AppComponent, ChildComponent, MyDirective]}); }); it('should update a loop', () => { TestBed.overrideTemplate( AppComponent, '<ul><li *ngFor="let item of items">{{item}}</li></ul>', ); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); let listItems = Array.from( (fixture.nativeElement as HTMLUListElement).querySelectorAll('li'), ); expect(listItems.map((li) => li.textContent)).toEqual(['first', 'second']); // change detection cycle, no model changes fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual(['first', 'second']); // remove the last item const items = fixture.componentInstance.items; items.length = 1; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual(['first']); // change an item items[0] = 'one'; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual(['one']); // add an item items.push('two'); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual(['one', 'two']); }); it('should support ngForOf context variables', () => { TestBed.overrideTemplate( AppComponent, '<ul><li *ngFor="let item of items; index as myIndex; count as myCount">{{myIndex}} of {{myCount}}: {{item}}</li></ul>', ); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); let listItems = Array.from( (fixture.nativeElement as HTMLUListElement).querySelectorAll('li'), ); expect(listItems.map((li) => li.textContent)).toEqual(['0 of 2: first', '1 of 2: second']); // add an item in the middle const items = fixture.componentInstance.items; items.splice(1, 0, 'middle'); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map((li) => li.textContent)).toEqual([ '0 of 3: first', '1 of 3: middle', '2 of 3: second', ]); }); it('should instantiate directives inside directives properly in an ngFor', () => { TestBed.overrideTemplate(AppComponent, '<app-child *ngFor="let item of items"></app-child>'); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const children = fixture.debugElement.queryAll(By.directive(ChildComponent)); // expect 2 children, each one with a directive expect(children.length).toBe(2); expect(children.map((child) => child.nativeElement.innerHTML)).toEqual([ '<div dir="">comp text</div>', '<div dir="">comp text</div>', ]); let directive = children[0].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); directive = children[1].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); // add an item const items = fixture.componentInstance.items; items.push('third'); fixture.detectChanges(); const childrenAfterAdd = fixture.debugElement.queryAll(By.directive(ChildComponent)); expect(childrenAfterAdd.length).toBe(3); expect(childrenAfterAdd.map((child) => child.nativeElement.innerHTML)).toEqual([ '<div dir="">comp text</div>', '<div dir="">comp text</div>', '<div dir="">comp text</div>', ]); directive = childrenAfterAdd[2].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); }); it('should retain parent view listeners when the NgFor destroy views', () => { @Component({ selector: 'app-toggle', template: `<button (click)="toggle()">Toggle List</button> <ul> <li *ngFor="let item of items">{{item}}</li> </ul>`, standalone: false, }) class ToggleComponent { private _data: number[] = [1, 2, 3]; items: number[] = []; toggle() { if (this.items.length) { this.items = []; } else { this.items = this._data; } } } TestBed.configureTestingModule({declarations: [ToggleComponent]}); const fixture = TestBed.createComponent(ToggleComponent); fixture.detectChanges(); // no elements in the list let listItems = Array.from( (fixture.nativeElement as HTMLUListElement).querySelectorAll('li'), ); expect(listItems.length).toBe(0); // this will fill the list fixture.componentInstance.toggle(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(3); expect(listItems.map((li) => li.textContent)).toEqual(['1', '2', '3']); // now toggle via the button const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(0); // toggle again button.click(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(3); });
{ "end_byte": 6766, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/common_integration_spec.ts" }
angular/packages/core/test/acceptance/common_integration_spec.ts_6772_12535
it('should support multiple levels of embedded templates', () => { @Component({ selector: 'app-multi', template: `<ul> <li *ngFor="let row of items"> <span *ngFor="let cell of row.data">{{cell}} - {{ row.value }} - {{ items.length }}</span> </li> </ul>`, standalone: false, }) class MultiLevelComponent { items: any[] = [ {data: ['1', '2'], value: 'first'}, {data: ['3', '4'], value: 'second'}, ]; } TestBed.configureTestingModule({declarations: [MultiLevelComponent]}); const fixture = TestBed.createComponent(MultiLevelComponent); fixture.detectChanges(); // change detection cycle, no model changes let listItems = Array.from( (fixture.nativeElement as HTMLUListElement).querySelectorAll('li'), ); expect(listItems.length).toBe(2); let spanItems = Array.from(listItems[0].querySelectorAll('span')); expect(spanItems.map((span) => span.textContent)).toEqual(['1 - first - 2', '2 - first - 2']); spanItems = Array.from(listItems[1].querySelectorAll('span')); expect(spanItems.map((span) => span.textContent)).toEqual([ '3 - second - 2', '4 - second - 2', ]); // remove the last item const items = fixture.componentInstance.items; items.length = 1; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(1); spanItems = Array.from(listItems[0].querySelectorAll('span')); expect(spanItems.map((span) => span.textContent)).toEqual(['1 - first - 1', '2 - first - 1']); // change an item items[0].data[0] = 'one'; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(1); spanItems = Array.from(listItems[0].querySelectorAll('span')); expect(spanItems.map((span) => span.textContent)).toEqual([ 'one - first - 1', '2 - first - 1', ]); // add an item items[1] = {data: ['three', '4'], value: 'third'}; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(2); spanItems = Array.from(listItems[0].querySelectorAll('span')); expect(spanItems.map((span) => span.textContent)).toEqual([ 'one - first - 2', '2 - first - 2', ]); spanItems = Array.from(listItems[1].querySelectorAll('span')); expect(spanItems.map((span) => span.textContent)).toEqual([ 'three - third - 2', '4 - third - 2', ]); }); it('should support multiple levels of embedded templates with listeners', () => { @Component({ selector: 'app-multi', template: `<div *ngFor="let row of items"> <p *ngFor="let cell of row.data"> <span (click)="onClick(row.value, name)"></span> {{ row.value }} - {{ name }} </p> </div>`, standalone: false, }) class MultiLevelWithListenerComponent { items: any[] = [{data: ['1'], value: 'first'}]; name = 'app'; events: string[] = []; onClick(value: string, name: string) { this.events.push(value, name); } } TestBed.configureTestingModule({declarations: [MultiLevelWithListenerComponent]}); const fixture = TestBed.createComponent(MultiLevelWithListenerComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('p'); expect(elements.length).toBe(1); expect(elements[0].innerHTML).toBe('<span></span> first - app '); const span: HTMLSpanElement = fixture.nativeElement.querySelector('span'); span.click(); expect(fixture.componentInstance.events).toEqual(['first', 'app']); fixture.componentInstance.name = 'new name'; fixture.detectChanges(); expect(elements[0].innerHTML).toBe('<span></span> first - new name '); span.click(); expect(fixture.componentInstance.events).toEqual(['first', 'app', 'first', 'new name']); }); it('should support skipping contexts', () => { @Component({ selector: 'app-multi', template: `<div *ngFor="let row of items"> <div *ngFor="let cell of row"> <span *ngFor="let span of cell.data">{{ cell.value }} - {{ name }}</span> </div> </div>`, standalone: false, }) class SkippingContextComponent { name = 'app'; items: any[] = [ [ // row {value: 'one', data: ['1', '2']}, // cell ], [{value: 'two', data: ['3', '4']}], ]; } TestBed.configureTestingModule({declarations: [SkippingContextComponent]}); const fixture = TestBed.createComponent(SkippingContextComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('span'); expect(elements.length).toBe(4); expect(elements[0].textContent).toBe('one - app'); expect(elements[1].textContent).toBe('one - app'); expect(elements[2].textContent).toBe('two - app'); expect(elements[3].textContent).toBe('two - app'); fixture.componentInstance.name = 'other'; fixture.detectChanges(); expect(elements[0].textContent).toBe('one - other'); expect(elements[1].textContent).toBe('one - other'); expect(elements[2].textContent).toBe('two - other'); expect(elements[3].textContent).toBe('two - other'); });
{ "end_byte": 12535, "start_byte": 6772, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/common_integration_spec.ts" }
angular/packages/core/test/acceptance/common_integration_spec.ts_12541_21985
it('should support context for 9+ levels of embedded templates', () => { @Component({ selector: 'app-multi', template: `<div *ngFor="let item0 of items"> <span *ngFor="let item1 of item0.data"> <span *ngFor="let item2 of item1.data"> <span *ngFor="let item3 of item2.data"> <span *ngFor="let item4 of item3.data"> <span *ngFor="let item5 of item4.data"> <span *ngFor="let item6 of item5.data"> <span *ngFor="let item7 of item6.data"> <span *ngFor="let item8 of item7.data">{{ item8 }}.{{ item7.value }}.{{ item6.value }}.{{ item5.value }}.{{ item4.value }}.{{ item3.value }}.{{ item2.value }}.{{ item1.value }}.{{ item0.value }}.{{ value }}</span> </span> </span> </span> </span> </span> </span> </span> </div>`, standalone: false, }) class NineLevelsComponent { value = 'App'; items: any[] = [ { // item0 data: [ { // item1 data: [ { // item2 data: [ { // item3 data: [ { // item4 data: [ { // item5 data: [ { // item6 data: [ { // item7 data: [ '1', '2', // item8 ], value: 'h', }, ], value: 'g', }, ], value: 'f', }, ], value: 'e', }, ], value: 'd', }, ], value: 'c', }, ], value: 'b', }, ], value: 'a', }, { // item0 data: [ { // item1 data: [ { // item2 data: [ { // item3 data: [ { // item4 data: [ { // item5 data: [ { // item6 data: [ { // item7 data: [ '3', '4', // item8 ], value: 'H', }, ], value: 'G', }, ], value: 'F', }, ], value: 'E', }, ], value: 'D', }, ], value: 'C', }, ], value: 'B', }, ], value: 'A', }, ]; } TestBed.configureTestingModule({declarations: [NineLevelsComponent]}); const fixture = TestBed.createComponent(NineLevelsComponent); fixture.detectChanges(); const divItems = (fixture.nativeElement as HTMLElement).querySelectorAll('div'); expect(divItems.length).toBe(2); // 2 outer loops let spanItems = divItems[0].querySelectorAll( 'span > span > span > span > span > span > span > span', ); expect(spanItems.length).toBe(2); // 2 inner elements expect(spanItems[0].textContent).toBe('1.h.g.f.e.d.c.b.a.App'); expect(spanItems[1].textContent).toBe('2.h.g.f.e.d.c.b.a.App'); spanItems = divItems[1].querySelectorAll( 'span > span > span > span > span > span > span > span', ); expect(spanItems.length).toBe(2); // 2 inner elements expect(spanItems[0].textContent).toBe('3.H.G.F.E.D.C.B.A.App'); expect(spanItems[1].textContent).toBe('4.H.G.F.E.D.C.B.A.App'); }); }); describe('ngIf', () => { it('should support sibling ngIfs', () => { @Component({ selector: 'app-multi', template: ` <div *ngIf="showing">{{ valueOne }}</div> <div *ngIf="showing">{{ valueTwo }}</div> `, standalone: false, }) class SimpleConditionComponent { showing = true; valueOne = 'one'; valueTwo = 'two'; } TestBed.configureTestingModule({declarations: [SimpleConditionComponent]}); const fixture = TestBed.createComponent(SimpleConditionComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('div'); expect(elements.length).toBe(2); expect(elements[0].textContent).toBe('one'); expect(elements[1].textContent).toBe('two'); fixture.componentInstance.valueOne = '$$one$$'; fixture.componentInstance.valueTwo = '$$two$$'; fixture.detectChanges(); expect(elements[0].textContent).toBe('$$one$$'); expect(elements[1].textContent).toBe('$$two$$'); }); it('should handle nested ngIfs with no intermediate context vars', () => { @Component({ selector: 'app-multi', template: `<div *ngIf="showing"> <div *ngIf="outerShowing"> <div *ngIf="innerShowing">{{ name }}</div> </div> </div> `, standalone: false, }) class NestedConditionsComponent { showing = true; outerShowing = true; innerShowing = true; name = 'App name'; } TestBed.configureTestingModule({declarations: [NestedConditionsComponent]}); const fixture = TestBed.createComponent(NestedConditionsComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('div'); expect(elements.length).toBe(3); expect(elements[2].textContent).toBe('App name'); fixture.componentInstance.name = 'Other name'; fixture.detectChanges(); expect(elements[2].textContent).toBe('Other name'); }); }); describe('NgTemplateOutlet', () => { it('should create and remove embedded views', () => { @Component({ selector: 'app-multi', template: `<ng-template #tpl>from tpl</ng-template> <ng-template [ngTemplateOutlet]="showing ? tpl : null"></ng-template> `, standalone: false, }) class EmbeddedViewsComponent { showing = false; } TestBed.configureTestingModule({declarations: [EmbeddedViewsComponent]}); const fixture = TestBed.createComponent(EmbeddedViewsComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); fixture.componentInstance.showing = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('from tpl'); fixture.componentInstance.showing = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); }); it('should create and remove embedded views', () => { @Component({ selector: 'app-multi', template: `<ng-template #tpl>from tpl</ng-template> <ng-container [ngTemplateOutlet]="showing ? tpl : null"></ng-container> `, standalone: false, }) class NgContainerComponent { showing = false; } TestBed.configureTestingModule({declarations: [NgContainerComponent]}); const fixture = TestBed.createComponent(NgContainerComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); fixture.componentInstance.showing = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('from tpl'); fixture.componentInstance.showing = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); }); }); });
{ "end_byte": 21985, "start_byte": 12541, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/common_integration_spec.ts" }
angular/packages/core/test/acceptance/host_binding_spec.ts_0_6074
/** * @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 {state, style, transition, trigger} from '@angular/animations'; import {CommonModule} from '@angular/common'; import { AfterContentInit, Component, ComponentRef, ContentChildren, Directive, DoCheck, HostBinding, HostListener, Injectable, Input, NgModule, OnChanges, OnInit, QueryList, ViewChild, ViewChildren, ViewContainerRef, } from '@angular/core'; import { bypassSanitizationTrustHtml, bypassSanitizationTrustStyle, bypassSanitizationTrustUrl, } from '@angular/core/src/sanitization/bypass'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; describe('host bindings', () => { it('should render host bindings on the root component', () => { @Component({ template: '...', standalone: false, }) class MyApp { @HostBinding('style') myStylesExp = {}; @HostBinding('class') myClassesExp = {}; } TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); const element = fixture.nativeElement; fixture.detectChanges(); const component = fixture.componentInstance; component.myStylesExp = {width: '100px'}; component.myClassesExp = 'foo'; fixture.detectChanges(); expect(element.style['width']).toEqual('100px'); expect(element.classList.contains('foo')).toBeTruthy(); component.myStylesExp = {width: '200px'}; component.myClassesExp = 'bar'; fixture.detectChanges(); expect(element.style['width']).toEqual('200px'); expect(element.classList.contains('foo')).toBeFalsy(); expect(element.classList.contains('bar')).toBeTruthy(); }); describe('defined in @Component', () => { it('should combine the inherited static classes of a parent and child component', () => { @Component({ template: '...', host: {'class': 'foo bar'}, standalone: false, }) class ParentCmp {} @Component({ template: '...', host: {'class': 'foo baz'}, standalone: false, }) class ChildCmp extends ParentCmp {} TestBed.configureTestingModule({declarations: [ChildCmp]}); const fixture = TestBed.createComponent(ChildCmp); fixture.detectChanges(); const element = fixture.nativeElement; expect(element.classList.contains('bar')).toBeTruthy(); expect(element.classList.contains('foo')).toBeTruthy(); expect(element.classList.contains('baz')).toBeTruthy(); }); it('should render host class and style on the root component', () => { @Component({ template: '...', host: {class: 'foo', style: 'color: red'}, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); const element = fixture.nativeElement; fixture.detectChanges(); expect(element.style['color']).toEqual('red'); expect(element.classList.contains('foo')).toBeTruthy(); }); it('should not cause problems if detectChanges is called when a property updates', () => { /** * Angular Material CDK Tree contains a code path whereby: * * 1. During the execution of a template function in which **more than one** property is * updated in a row. * 2. A property that **is not the last property** is updated in the **original template**: * - That sets up a new observable and subscribes to it * - The new observable it sets up can emit synchronously. * - When it emits, it calls `detectChanges` on a `ViewRef` that it has a handle to * - That executes a **different template**, that has host bindings * - this executes `setHostBindings` * - Inside of `setHostBindings` we are currently updating the selected index **global * state** via `setSelectedIndex`. * 3. We attempt to update the next property in the **original template**. * - But the selected index has been altered, and we get errors. */ @Component({ selector: 'child', template: `...`, standalone: false, }) class ChildCmp {} @Component({ selector: 'parent', template: ` <div> <div #template></div> <p>{{prop}}</p> <p>{{prop2}}</p> </div> `, host: { '[style.color]': 'color', }, standalone: false, }) class ParentCmp { private _prop = ''; @ViewChild('template', {read: ViewContainerRef}) vcr: ViewContainerRef = null!; private child: ComponentRef<ChildCmp> = null!; @Input() set prop(value: string) { // Material CdkTree has at least one scenario where setting a property causes a data // source // to update, which causes a synchronous call to detectChanges(). this._prop = value; if (this.child) { this.child.changeDetectorRef.detectChanges(); } } get prop() { return this._prop; } @Input() prop2 = 0; ngAfterViewInit() { this.child = this.vcr.createComponent(ChildCmp); } } @Component({ template: `<parent [prop]="prop" [prop2]="prop2"></parent>`, standalone: false, }) class App { prop = 'a'; prop2 = 1; } TestBed.configureTestingModule({declarations: [App, ParentCmp, ChildCmp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.prop = 'b'; fixture.componentInstance.prop2 = 2; fixture.detectChanges(); }); });
{ "end_byte": 6074, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_binding_spec.ts" }
angular/packages/core/test/acceptance/host_binding_spec.ts_6078_15774
describe('with synthetic (animations) props', () => { it('should work when directive contains synthetic props', () => { @Directive({ selector: '[animationPropDir]', standalone: false, }) class AnimationPropDir { @HostBinding('@myAnimation') myAnimation: string = 'color'; } @Component({ selector: 'my-comp', template: '<div animationPropDir>Some content</div>', animations: [trigger('myAnimation', [state('color', style({color: 'red'}))])], standalone: false, }) class Comp {} TestBed.configureTestingModule({ declarations: [Comp, AnimationPropDir], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const queryResult = fixture.debugElement.query(By.directive(AnimationPropDir)); expect(queryResult.nativeElement.style.color).toBe('red'); }); it('should work when directive contains synthetic props and directive is applied to a component', () => { @Directive({ selector: '[animationPropDir]', standalone: false, }) class AnimationPropDir { @HostBinding('@myAnimation') myAnimation: string = 'color'; } @Component({ selector: 'my-comp', template: 'Some content', animations: [trigger('myAnimation', [state('color', style({color: 'red'}))])], standalone: false, }) class Comp {} @Component({ selector: 'app', template: '<my-comp animationPropDir></my-comp>', animations: [trigger('myAnimation', [state('color', style({color: 'green'}))])], standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Comp, AnimationPropDir], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const queryResult = fixture.debugElement.query(By.directive(AnimationPropDir)); expect(queryResult.nativeElement.style.color).toBe('green'); }); it('should work when component contains synthetic props', () => { @Component({ selector: 'my-comp', template: '<div>Some content/div>', animations: [trigger('myAnimation', [state('color', style({color: 'red'}))])], standalone: false, }) class Comp { @HostBinding('@myAnimation') myAnimation: string = 'color'; } TestBed.configureTestingModule({ declarations: [Comp], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.nativeElement.style.color).toBe('red'); }); it('should work when child component contains synthetic props', () => { @Component({ selector: 'my-comp', template: '<div>Some content/div>', animations: [trigger('myAnimation', [state('color', style({color: 'red'}))])], standalone: false, }) class Comp { @HostBinding('@myAnimation') myAnimation: string = 'color'; } @Component({ template: '<my-comp></my-comp>', standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Comp], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const queryResult = fixture.debugElement.query(By.directive(Comp)); expect(queryResult.nativeElement.style.color).toBe('red'); }); it('should work when component extends a directive that contains synthetic props', () => { @Directive({ selector: 'animation-dir', standalone: false, }) class AnimationDir { @HostBinding('@myAnimation') myAnimation: string = 'color'; } @Component({ selector: 'my-comp', template: '<div>Some content</div>', animations: [trigger('myAnimation', [state('color', style({color: 'red'}))])], standalone: false, }) class Comp extends AnimationDir {} TestBed.configureTestingModule({ declarations: [Comp, AnimationDir], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.nativeElement.style.color).toBe('red'); }); it('should work when directive contains synthetic listeners', async () => { const events: string[] = []; @Directive({ selector: '[animationPropDir]', standalone: false, }) class AnimationPropDir { @HostBinding('@myAnimation') myAnimation: string = 'a'; @HostListener('@myAnimation.start') onAnimationStart() { events.push('@myAnimation.start'); } @HostListener('@myAnimation.done') onAnimationDone() { events.push('@myAnimation.done'); } } @Component({ selector: 'my-comp', template: '<div animationPropDir>Some content</div>', animations: [ trigger('myAnimation', [state('a', style({color: 'yellow'})), transition('* => a', [])]), ], standalone: false, }) class Comp {} TestBed.configureTestingModule({ declarations: [Comp, AnimationPropDir], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); await fixture.whenStable(); // wait for animations to complete const queryResult = fixture.debugElement.query(By.directive(AnimationPropDir)); expect(queryResult.nativeElement.style.color).toBe('yellow'); expect(events).toEqual(['@myAnimation.start', '@myAnimation.done']); }); it('should work when component contains synthetic listeners', async () => { const events: string[] = []; @Component({ selector: 'my-comp', template: '<div>Some content</div>', animations: [ trigger('myAnimation', [state('a', style({color: 'yellow'})), transition('* => a', [])]), ], standalone: false, }) class Comp { @HostBinding('@myAnimation') myAnimation: string = 'a'; @HostListener('@myAnimation.start') onAnimationStart() { events.push('@myAnimation.start'); } @HostListener('@myAnimation.done') onAnimationDone() { events.push('@myAnimation.done'); } } TestBed.configureTestingModule({ declarations: [Comp], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); await fixture.whenStable(); // wait for animations to complete expect(fixture.nativeElement.style.color).toBe('yellow'); expect(events).toEqual(['@myAnimation.start', '@myAnimation.done']); }); it('should work when child component contains synthetic listeners', async () => { const events: string[] = []; @Component({ selector: 'my-comp', template: '<div>Some content</div>', animations: [ trigger('myAnimation', [state('a', style({color: 'yellow'})), transition('* => a', [])]), ], standalone: false, }) class Comp { @HostBinding('@myAnimation') myAnimation: string = 'a'; @HostListener('@myAnimation.start') onAnimationStart() { events.push('@myAnimation.start'); } @HostListener('@myAnimation.done') onAnimationDone() { events.push('@myAnimation.done'); } } @Component({ template: '<my-comp></my-comp>', standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Comp], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); await fixture.whenStable(); // wait for animations to complete const queryResult = fixture.debugElement.query(By.directive(Comp)); expect(queryResult.nativeElement.style.color).toBe('yellow'); expect(events).toEqual(['@myAnimation.start', '@myAnimation.done']); }); it('should work when component extends a directive that contains synthetic listeners', async () => { const events: string[] = []; @Directive({ selector: 'animation-dir', standalone: false, }) class AnimationDir { @HostBinding('@myAnimation') myAnimation: string = 'a'; @HostListener('@myAnimation.start') onAnimationStart() { events.push('@myAnimation.start'); } @HostListener('@myAnimation.done') onAnimationDone() { events.push('@myAnimation.done'); } } @Component({ selector: 'my-comp', template: '<div>Some content</div>', animations: [ trigger('myAnimation', [state('a', style({color: 'yellow'})), transition('* => a', [])]), ], standalone: false, }) class Comp extends AnimationDir {} TestBed.configureTestingModule({ declarations: [Comp], imports: [NoopAnimationsModule], }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); await fixture.whenStable(); // wait for animations to complete expect(fixture.nativeElement.style.color).toBe('yellow'); expect(events).toEqual(['@myAnimation.start', '@myAnimation.done']); }); });
{ "end_byte": 15774, "start_byte": 6078, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_binding_spec.ts" }
angular/packages/core/test/acceptance/host_binding_spec.ts_15778_24017
describe('via @HostBinding', () => { it('should render styling for parent and sub-classed components in order', () => { @Component({ template: ` <child-and-parent-cmp></child-and-parent-cmp> `, standalone: false, }) class MyApp {} @Component({ template: '...', standalone: false, }) class ParentCmp { @HostBinding('style.width') width1 = '100px'; @HostBinding('style.height') height1 = '100px'; @HostBinding('style.opacity') opacity1 = '0.5'; } @Component({ selector: 'child-and-parent-cmp', template: '...', standalone: false, }) class ChildCmp extends ParentCmp { @HostBinding('style.width') width2 = '200px'; @HostBinding('style.height') height2 = '200px'; } TestBed.configureTestingModule({declarations: [MyApp, ParentCmp, ChildCmp]}); const fixture = TestBed.createComponent(MyApp); const element = fixture.nativeElement; fixture.detectChanges(); const childElement = element.querySelector('child-and-parent-cmp'); expect(childElement.style.width).toEqual('200px'); expect(childElement.style.height).toEqual('200px'); expect(childElement.style.opacity).toEqual('0.5'); }); it('should prioritize styling present in the order of directive hostBinding evaluation, but consider sub-classed directive styling to be the most important', () => { @Component({ template: '<div child-dir sibling-dir></div>', standalone: false, }) class MyApp {} @Directive({ selector: '[parent-dir]', standalone: false, }) class ParentDir { @HostBinding('style.width') get width1() { return '100px'; } @HostBinding('style.height') get height1() { return '100px'; } @HostBinding('style.color') get color1() { return 'red'; } } @Directive({ selector: '[child-dir]', standalone: false, }) class ChildDir extends ParentDir { @HostBinding('style.width') get width2() { return '200px'; } @HostBinding('style.height') get height2() { return '200px'; } } @Directive({ selector: '[sibling-dir]', standalone: false, }) class SiblingDir { @HostBinding('style.width') get width3() { return '300px'; } @HostBinding('style.height') get height3() { return '300px'; } @HostBinding('style.opacity') get opacity3() { return '0.5'; } @HostBinding('style.color') get color1() { return 'blue'; } } TestBed.configureTestingModule({declarations: [MyApp, ParentDir, SiblingDir, ChildDir]}); const fixture = TestBed.createComponent(MyApp); const element = fixture.nativeElement; fixture.detectChanges(); const childElement = element.querySelector('div'); // width/height values were set in all directives, but the sub-class directive // (ChildDir) had priority over the parent directive (ParentDir) which is why its // value won. It also won over Dir because the SiblingDir directive was declared // later in `declarations`. expect(childElement.style.width).toEqual('200px'); expect(childElement.style.height).toEqual('200px'); // ParentDir styled the color first before Dir expect(childElement.style.color).toEqual('red'); // Dir was the only directive to style opacity expect(childElement.style.opacity).toEqual('0.5'); }); it('should allow class-bindings to be placed on ng-container elements', () => { @Component({ template: ` <ng-container [class.foo]="true" dir-that-adds-other-classes>...</ng-container> `, standalone: false, }) class MyApp {} @Directive({ selector: '[dir-that-adds-other-classes]', standalone: false, }) class DirThatAddsOtherClasses { @HostBinding('class.other-class') bool = true; } TestBed.configureTestingModule({declarations: [MyApp, DirThatAddsOtherClasses]}); expect(() => { const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); }).not.toThrow(); }); }); @Directive({ selector: '[hostBindingDir]', standalone: false, }) class HostBindingDir { @HostBinding() id = 'foo'; } it('should support host bindings in directives', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @HostBinding('className') klass = 'foo'; } @Component({ template: '<span dir></span>', standalone: false, }) class App { @ViewChild(Dir) directiveInstance!: Dir; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); const element = fixture.nativeElement; fixture.detectChanges(); expect(element.innerHTML).toContain('class="foo"'); fixture.componentInstance.directiveInstance.klass = 'bar'; fixture.detectChanges(); expect(element.innerHTML).toContain('class="bar"'); }); it('should support host bindings on root component', () => { @Component({ template: '', standalone: false, }) class HostBindingComp { @HostBinding() title = 'my-title'; } TestBed.configureTestingModule({declarations: [HostBindingComp]}); const fixture = TestBed.createComponent(HostBindingComp); const element = fixture.nativeElement; fixture.detectChanges(); expect(element.title).toBe('my-title'); fixture.componentInstance.title = 'other-title'; fixture.detectChanges(); expect(element.title).toBe('other-title'); }); it('should support host bindings on nodes with providers', () => { @Injectable() class ServiceOne { value = 'one'; } @Injectable() class ServiceTwo { value = 'two'; } @Component({ template: '', providers: [ServiceOne, ServiceTwo], standalone: false, }) class App { constructor( public serviceOne: ServiceOne, public serviceTwo: ServiceTwo, ) {} @HostBinding() title = 'my-title'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); const element = fixture.nativeElement; fixture.detectChanges(); expect(element.title).toBe('my-title'); expect(fixture.componentInstance.serviceOne.value).toEqual('one'); expect(fixture.componentInstance.serviceTwo.value).toEqual('two'); fixture.componentInstance.title = 'other-title'; fixture.detectChanges(); expect(element.title).toBe('other-title'); }); it('should support host bindings on multiple nodes', () => { @Directive({ selector: '[someDir]', standalone: false, }) class SomeDir {} @Component({ selector: 'host-title-comp', template: '', standalone: false, }) class HostTitleComp { @HostBinding() title = 'my-title'; } @Component({ template: ` <div hostBindingDir></div> <div someDir></div> <host-title-comp></host-title-comp> `, standalone: false, }) class App { @ViewChild(HostBindingDir) hostBindingDir!: HostBindingDir; } TestBed.configureTestingModule({declarations: [App, SomeDir, HostTitleComp, HostBindingDir]}); const fixture = TestBed.createComponent(App); const element = fixture.nativeElement; fixture.detectChanges(); const hostBindingDiv = element.querySelector('div') as HTMLElement; const hostTitleComp = element.querySelector('host-title-comp') as HTMLElement; expect(hostBindingDiv.id).toEqual('foo'); expect(hostTitleComp.title).toEqual('my-title'); fixture.componentInstance.hostBindingDir!.id = 'bar'; fixture.detectChanges(); expect(hostBindingDiv.id).toEqual('bar'); });
{ "end_byte": 24017, "start_byte": 15778, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_binding_spec.ts" }
angular/packages/core/test/acceptance/host_binding_spec.ts_24021_32064
it('should support consecutive components with host bindings', () => { @Component({ selector: 'host-binding-comp', template: '', standalone: false, }) class HostBindingComp { @HostBinding() id = 'blue'; } @Component({ template: ` <host-binding-comp></host-binding-comp> <host-binding-comp></host-binding-comp> `, standalone: false, }) class App { @ViewChildren(HostBindingComp) hostBindingComp!: QueryList<HostBindingComp>; } TestBed.configureTestingModule({declarations: [App, HostBindingComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const comps = fixture.componentInstance.hostBindingComp.toArray(); const hostBindingEls = fixture.nativeElement.querySelectorAll( 'host-binding-comp', ) as NodeListOf<HTMLElement>; expect(hostBindingEls.length).toBe(2); comps[0].id = 'red'; fixture.detectChanges(); expect(hostBindingEls[0].id).toBe('red'); // second element should not be affected expect(hostBindingEls[1].id).toBe('blue'); comps[1].id = 'red'; fixture.detectChanges(); // now second element should take updated value expect(hostBindingEls[1].id).toBe('red'); }); it('should support dirs with host bindings on the same node as dirs without host bindings', () => { @Directive({ selector: '[someDir]', standalone: false, }) class SomeDir {} @Component({ template: '<div someDir hostBindingDir></div>', standalone: false, }) class App { @ViewChild(HostBindingDir) hostBindingDir!: HostBindingDir; } TestBed.configureTestingModule({declarations: [App, SomeDir, HostBindingDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostBindingDiv = fixture.nativeElement.querySelector('div') as HTMLElement; expect(hostBindingDiv.id).toEqual('foo'); fixture.componentInstance.hostBindingDir!.id = 'bar'; fixture.detectChanges(); expect(hostBindingDiv.id).toEqual('bar'); }); it('should support host bindings that rely on values from init hooks', () => { @Component({ template: '', selector: 'init-hook-comp', standalone: false, }) class InitHookComp implements OnInit, OnChanges, DoCheck { @Input() inputValue = ''; changesValue = ''; initValue = ''; checkValue = ''; ngOnChanges() { this.changesValue = 'changes'; } ngOnInit() { this.initValue = 'init'; } ngDoCheck() { this.checkValue = 'check'; } @HostBinding('title') get value() { return `${this.inputValue}-${this.changesValue}-${this.initValue}-${this.checkValue}`; } } @Component({ template: '<init-hook-comp [inputValue]="value"></init-hook-comp>', standalone: false, }) class App { value = 'input'; } TestBed.configureTestingModule({declarations: [App, InitHookComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const initHookComp = fixture.nativeElement.querySelector('init-hook-comp') as HTMLElement; expect(initHookComp.title).toEqual('input-changes-init-check'); fixture.componentInstance.value = 'input2'; fixture.detectChanges(); expect(initHookComp.title).toEqual('input2-changes-init-check'); }); it('should support host bindings with the same name as inputs', () => { @Directive({ selector: '[hostBindingDir]', standalone: false, }) class HostBindingInputDir { @Input() disabled = false; @HostBinding('disabled') hostDisabled = false; } @Component({ template: '<input hostBindingDir [disabled]="isDisabled">', standalone: false, }) class App { @ViewChild(HostBindingInputDir) hostBindingInputDir!: HostBindingInputDir; isDisabled = true; } TestBed.configureTestingModule({declarations: [App, HostBindingInputDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostBindingInputDir = fixture.componentInstance.hostBindingInputDir; const hostBindingEl = fixture.nativeElement.querySelector('input') as HTMLInputElement; expect(hostBindingInputDir.disabled).toBe(true); expect(hostBindingEl.disabled).toBe(false); fixture.componentInstance.isDisabled = false; fixture.detectChanges(); expect(hostBindingInputDir.disabled).toBe(false); expect(hostBindingEl.disabled).toBe(false); hostBindingInputDir.hostDisabled = true; fixture.detectChanges(); expect(hostBindingInputDir.disabled).toBe(false); expect(hostBindingEl.disabled).toBe(true); }); it('should support host bindings on second template pass', () => { @Component({ selector: 'parent', template: '<div hostBindingDir></div>', standalone: false, }) class Parent {} @Component({ template: ` <parent></parent> <parent></parent> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Parent, HostBindingDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const divs = fixture.nativeElement.querySelectorAll('div'); expect(divs[0].id).toEqual('foo'); expect(divs[1].id).toEqual('foo'); }); it('should support host bindings in for loop', () => { @Component({ template: ` <div *ngFor="let row of rows"> <p hostBindingDir></p> </div> `, standalone: false, }) class App { rows: number[] = []; } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App, HostBindingDir]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.rows = [1, 2, 3]; fixture.detectChanges(); const paragraphs = fixture.nativeElement.querySelectorAll('p'); expect(paragraphs[0].id).toEqual('foo'); expect(paragraphs[1].id).toEqual('foo'); expect(paragraphs[2].id).toEqual('foo'); }); it('should support component with host bindings and array literals', () => { @Component({ selector: 'host-binding-comp', template: '', standalone: false, }) class HostBindingComp { @HostBinding() id = 'my-id'; } @Component({ selector: 'name-comp', template: '', standalone: false, }) class NameComp { @Input() names!: string[]; } @Component({ template: ` <name-comp [names]="['Nancy', name, 'Ned']"></name-comp> <host-binding-comp></host-binding-comp> `, standalone: false, }) class App { @ViewChild(NameComp) nameComp!: NameComp; name = ''; } TestBed.configureTestingModule({declarations: [App, HostBindingComp, NameComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const nameComp = fixture.componentInstance.nameComp; const hostBindingEl = fixture.nativeElement.querySelector('host-binding-comp') as HTMLElement; fixture.componentInstance.name = 'Betty'; fixture.detectChanges(); expect(hostBindingEl.id).toBe('my-id'); expect(nameComp.names).toEqual(['Nancy', 'Betty', 'Ned']); const firstArray = nameComp.names; fixture.detectChanges(); expect(firstArray).toBe(nameComp.names); fixture.componentInstance.name = 'my-id'; fixture.detectChanges(); expect(hostBindingEl.id).toBe('my-id'); expect(nameComp.names).toEqual(['Nancy', 'my-id', 'Ned']); }); // Note: This is a contrived example. For feature parity with render2, we should make sure it // works in this way (see https://stackblitz.com/edit/angular-cbqpbe), but a more realistic // example would be an animation host binding with a literal defining the animation config. // When animation support is added, we should add another test for that case.
{ "end_byte": 32064, "start_byte": 24021, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_binding_spec.ts" }
angular/packages/core/test/acceptance/host_binding_spec.ts_32067_40688
it('should support host bindings that contain array literals', () => { @Component({ selector: 'name-comp', template: '', standalone: false, }) class NameComp { @Input() names!: string[]; } @Component({ selector: 'host-binding-comp', host: {'[id]': `['red', id]`, '[dir]': `dir`, '[title]': `[title, otherTitle]`}, template: '', standalone: false, }) class HostBindingComp { id = 'blue'; dir = 'ltr'; title = 'my title'; otherTitle = 'other title'; } @Component({ template: ` <name-comp [names]="[name, 'Nancy', otherName]"></name-comp> <host-binding-comp></host-binding-comp> `, standalone: false, }) class App { @ViewChild(HostBindingComp) hostBindingComp!: HostBindingComp; @ViewChild(NameComp) nameComp!: NameComp; name = ''; otherName = ''; } TestBed.configureTestingModule({declarations: [App, HostBindingComp, NameComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {nameComp, hostBindingComp} = fixture.componentInstance; fixture.componentInstance.name = 'Frank'; fixture.componentInstance.otherName = 'Joe'; fixture.detectChanges(); const hostBindingEl = fixture.nativeElement.querySelector('host-binding-comp') as HTMLElement; expect(hostBindingEl.id).toBe('red,blue'); expect(hostBindingEl.dir).toBe('ltr'); expect(hostBindingEl.title).toBe('my title,other title'); expect(nameComp!.names).toEqual(['Frank', 'Nancy', 'Joe']); const firstArray = nameComp!.names; fixture.detectChanges(); expect(firstArray).toBe(nameComp!.names); hostBindingComp.id = 'green'; hostBindingComp.dir = 'rtl'; hostBindingComp.title = 'TITLE'; fixture.detectChanges(); expect(hostBindingEl.id).toBe('red,green'); expect(hostBindingEl.dir).toBe('rtl'); expect(hostBindingEl.title).toBe('TITLE,other title'); }); it('should support directives with and without allocHostVars on the same component', () => { let events: string[] = []; @Directive({ selector: '[hostDir]', host: {'[title]': `[title, 'other title']`}, standalone: false, }) class HostBindingDir { title = 'my title'; } @Directive({ selector: '[hostListenerDir]', standalone: false, }) class HostListenerDir { @HostListener('click') onClick() { events.push('click!'); } } @Component({ template: '<button hostListenerDir hostDir>Click</button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, HostBindingDir, HostListenerDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button')!; button.click(); expect(events).toEqual(['click!']); expect(button.title).toEqual('my title,other title'); }); it('should support host bindings with literals from multiple directives', () => { @Component({ selector: 'host-binding-comp', host: {'[id]': `['red', id]`}, template: '', standalone: false, }) class HostBindingComp { id = 'blue'; } @Directive({ selector: '[hostDir]', host: {'[title]': `[title, 'other title']`}, standalone: false, }) class HostBindingDir { title = 'my title'; } @Component({ template: '<host-binding-comp hostDir></host-binding-comp>', standalone: false, }) class App { @ViewChild(HostBindingComp) hostBindingComp!: HostBindingComp; @ViewChild(HostBindingDir) hostBindingDir!: HostBindingDir; } TestBed.configureTestingModule({declarations: [App, HostBindingComp, HostBindingDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostElement = fixture.nativeElement.querySelector('host-binding-comp') as HTMLElement; expect(hostElement.id).toBe('red,blue'); expect(hostElement.title).toBe('my title,other title'); fixture.componentInstance.hostBindingDir.title = 'blue'; fixture.detectChanges(); expect(hostElement.title).toBe('blue,other title'); fixture.componentInstance.hostBindingComp.id = 'green'; fixture.detectChanges(); expect(hostElement.id).toBe('red,green'); }); it('should support ternary expressions in host bindings', () => { @Component({ selector: 'host-binding-comp', template: '', host: { // Use `attr` since IE doesn't support the `title` property on all elements. '[attr.id]': `condition ? ['red', id] : 'green'`, '[attr.title]': `otherCondition ? [title] : 'other title'`, }, standalone: false, }) class HostBindingComp { condition = true; otherCondition = true; id = 'blue'; title = 'blue'; } @Component({ template: `<host-binding-comp></host-binding-comp>{{ name }}`, standalone: false, }) class App { @ViewChild(HostBindingComp) hostBindingComp!: HostBindingComp; name = ''; } TestBed.configureTestingModule({declarations: [App, HostBindingComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostElement = fixture.nativeElement.querySelector('host-binding-comp') as HTMLElement; fixture.componentInstance.name = 'Ned'; fixture.detectChanges(); expect(hostElement.id).toBe('red,blue'); expect(hostElement.title).toBe('blue'); expect(fixture.nativeElement.innerHTML.endsWith('Ned')).toBe(true); fixture.componentInstance.hostBindingComp.condition = false; fixture.componentInstance.hostBindingComp.title = 'TITLE'; fixture.detectChanges(); expect(hostElement.id).toBe('green'); expect(hostElement.title).toBe('TITLE'); fixture.componentInstance.hostBindingComp.otherCondition = false; fixture.detectChanges(); expect(hostElement.id).toBe('green'); expect(hostElement.title).toBe('other title'); }); it('should merge attributes on host and template', () => { @Directive({ selector: '[dir1]', host: {id: 'dir1'}, standalone: false, }) class MyDir1 {} @Directive({ selector: '[dir2]', host: {id: 'dir2'}, standalone: false, }) class MyDir2 {} @Component({ template: `<div dir1 dir2 id="tmpl"></div>`, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyComp, MyDir1, MyDir2]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const div: HTMLElement = fixture.debugElement.nativeElement.firstChild; expect(div.id).toEqual('tmpl'); }); it('should work correctly with inherited directives with hostBindings', () => { @Directive({ selector: '[superDir]', host: {'[id]': 'id'}, standalone: false, }) class SuperDirective { id = 'my-id'; } @Directive({ selector: '[subDir]', host: {'[title]': 'title'}, standalone: false, }) class SubDirective extends SuperDirective { title = 'my-title'; } @Component({ template: ` <div subDir></div> <div superDir></div> `, standalone: false, }) class App { @ViewChild(SubDirective) subDir!: SubDirective; @ViewChild(SuperDirective) superDir!: SuperDirective; } TestBed.configureTestingModule({declarations: [App, SuperDirective, SubDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const els = fixture.nativeElement.querySelectorAll('div') as NodeListOf<HTMLElement>; const firstDivEl = els[0]; const secondDivEl = els[1]; // checking first div element with inherited directive expect(firstDivEl.id).toEqual('my-id'); expect(firstDivEl.title).toEqual('my-title'); fixture.componentInstance.subDir.title = 'new-title'; fixture.detectChanges(); expect(firstDivEl.id).toEqual('my-id'); expect(firstDivEl.title).toEqual('new-title'); fixture.componentInstance.subDir.id = 'new-id'; fixture.detectChanges(); expect(firstDivEl.id).toEqual('new-id'); expect(firstDivEl.title).toEqual('new-title'); // checking second div element with simple directive expect(secondDivEl.id).toEqual('my-id'); fixture.componentInstance.superDir.id = 'new-id'; fixture.detectChanges(); expect(secondDivEl.id).toEqual('new-id'); });
{ "end_byte": 40688, "start_byte": 32067, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_binding_spec.ts" }
angular/packages/core/test/acceptance/host_binding_spec.ts_40692_48572
it('should support host attributes', () => { @Directive({ selector: '[hostAttributeDir]', host: {'role': 'listbox'}, standalone: false, }) class HostAttributeDir {} @Component({ template: '<div hostAttributeDir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, HostAttributeDir]}); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toContain(`role="listbox"`); }); it('should support content children in host bindings', () => { @Component({ selector: 'host-binding-comp', template: '<ng-content></ng-content>', host: {'[id]': 'foos.length'}, standalone: false, }) class HostBindingWithContentChildren { @ContentChildren('foo') foos!: QueryList<any>; } @Component({ template: ` <host-binding-comp> <div #foo></div> <div #foo></div> </host-binding-comp> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, HostBindingWithContentChildren]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostBindingEl = fixture.nativeElement.querySelector('host-binding-comp') as HTMLElement; expect(hostBindingEl.id).toEqual('2'); }); it('should support host bindings dependent on content hooks', () => { @Component({ selector: 'host-binding-comp', template: '', host: {'[id]': 'myValue'}, standalone: false, }) class HostBindingWithContentHooks implements AfterContentInit { myValue = 'initial'; ngAfterContentInit() { this.myValue = 'after-content'; } } @Component({ template: '<host-binding-comp></host-binding-comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, HostBindingWithContentHooks]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostBindingEl = fixture.nativeElement.querySelector('host-binding-comp') as HTMLElement; expect(hostBindingEl.id).toEqual('after-content'); }); describe('styles', () => { it('should bind to host styles', () => { @Component({ selector: 'host-binding-to-styles', host: {'[style.width.px]': 'width'}, template: '', standalone: false, }) class HostBindingToStyles { width = 2; } @Component({ template: '<host-binding-to-styles></host-binding-to-styles>', standalone: false, }) class App { @ViewChild(HostBindingToStyles) hostBindingDir!: HostBindingToStyles; } TestBed.configureTestingModule({declarations: [App, HostBindingToStyles]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostBindingEl = fixture.nativeElement.querySelector( 'host-binding-to-styles', ) as HTMLElement; expect(hostBindingEl.style.width).toEqual('2px'); fixture.componentInstance.hostBindingDir.width = 5; fixture.detectChanges(); expect(hostBindingEl.style.width).toEqual('5px'); }); it('should bind to host styles on containers', () => { @Directive({ selector: '[hostStyles]', host: {'[style.width.px]': 'width'}, standalone: false, }) class HostBindingToStyles { width = 2; } @Directive({ selector: '[containerDir]', standalone: false, }) class ContainerDir { constructor(public vcr: ViewContainerRef) {} } @Component({ template: '<div hostStyles containerDir></div>', standalone: false, }) class App { @ViewChild(HostBindingToStyles) hostBindingDir!: HostBindingToStyles; } TestBed.configureTestingModule({declarations: [App, HostBindingToStyles, ContainerDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostBindingEl = fixture.nativeElement.querySelector('div') as HTMLElement; expect(hostBindingEl.style.width).toEqual('2px'); fixture.componentInstance.hostBindingDir.width = 5; fixture.detectChanges(); expect(hostBindingEl.style.width).toEqual('5px'); }); it('should apply static host classes', () => { @Component({ selector: 'static-host-class', host: {'class': 'mat-toolbar'}, template: '', standalone: false, }) class StaticHostClass {} @Component({ template: '<static-host-class></static-host-class>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, StaticHostClass]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostBindingEl = fixture.nativeElement.querySelector('static-host-class') as HTMLElement; expect(hostBindingEl.className).toEqual('mat-toolbar'); }); }); describe('sanitization', () => { function identity(value: any) { return value; } function verify( tag: string, prop: string, value: any, expectedSanitizedValue: any, bypassFn: Function, isAttribute: boolean = true, throws: boolean = false, ) { it(`should sanitize <${tag} ${prop}> ${isAttribute ? 'properties' : 'attributes'}`, () => { @Directive({ selector: '[unsafeUrlHostBindingDir]', host: { [`[${isAttribute ? 'attr.' : ''}${prop}]`]: 'value', }, standalone: false, }) class UnsafeDir { value: any = value; } @Component({ template: `<${tag} unsafeUrlHostBindingDir></${tag}>`, standalone: false, }) class App { @ViewChild(UnsafeDir) unsafeDir!: UnsafeDir; } TestBed.configureTestingModule({declarations: [App, UnsafeDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const el = fixture.nativeElement.querySelector(tag)!; const current = () => (isAttribute ? el.getAttribute(prop) : (el as any)[prop]); fixture.componentInstance.unsafeDir.value = value; fixture.detectChanges(); expect(current()).toEqual(expectedSanitizedValue); fixture.componentInstance.unsafeDir.value = bypassFn(value); if (throws) { expect(() => fixture.detectChanges()).toThrowError(/Required a safe URL, got a \w+/); } else { fixture.detectChanges(); expect(current()).toEqual(bypassFn == identity ? expectedSanitizedValue : value); } }); } verify( 'a', 'href', 'javascript:alert(1)', 'unsafe:javascript:alert(1)', bypassSanitizationTrustUrl, ); verify('a', 'href', 'javascript:alert(1.1)', 'unsafe:javascript:alert(1.1)', identity); verify( 'a', 'href', 'javascript:alert(1.2)', 'unsafe:javascript:alert(1.2)', bypassSanitizationTrustStyle, true, true, ); verify( 'blockquote', 'cite', 'javascript:alert(2)', 'unsafe:javascript:alert(2)', bypassSanitizationTrustUrl, ); verify('blockquote', 'cite', 'javascript:alert(2.1)', 'unsafe:javascript:alert(2.1)', identity); verify( 'blockquote', 'cite', 'javascript:alert(2.2)', 'unsafe:javascript:alert(2.2)', bypassSanitizationTrustHtml, true, true, ); verify( 'b', 'innerHTML', '<img src="javascript:alert(3)">', '<img src="unsafe:javascript:alert(3)">', bypassSanitizationTrustHtml, /* isAttribute */ false, ); });
{ "end_byte": 48572, "start_byte": 40692, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_binding_spec.ts" }
angular/packages/core/test/acceptance/host_binding_spec.ts_48576_52485
describe('host binding on containers', () => { @Directive({ selector: '[staticHostAtt]', host: {'static': 'attr'}, standalone: false, }) class StaticHostAttr { constructor() {} } @Directive({ selector: '[dynamicHostAtt]', host: {'[attr.dynamic]': '"dynamic"'}, standalone: false, }) class DynamicHostAttr { constructor() {} } it('should fail with expected error with ng-container', () => { @Component({ selector: 'my-app', template: ` <ng-template #ref></ng-template> <ng-container [ngTemplateOutlet]="ref" staticHostAtt dynamicHostAtt></ng-container> `, standalone: false, }) class App {} const comp = TestBed.configureTestingModule({ declarations: [App, StaticHostAttr, DynamicHostAttr], }).createComponent(App); // TODO(FW-2202): binding static attrs won't throw an error. We should be more consistent. expect(() => comp.detectChanges()).toThrowError( /Attempted to set attribute `dynamic` on a container node. Host bindings are not valid on ng-container or ng-template./, ); }); it('should fail with expected error with ng-template', () => { @Component({ selector: 'my-app', template: ` <ng-template staticHostAtt dynamicHostAtt></ng-template> `, standalone: false, }) class App {} const comp = TestBed.configureTestingModule({ declarations: [App, StaticHostAttr, DynamicHostAttr], }).createComponent(App); // TODO(FW-2202): binding static attrs won't throw an error. We should be more consistent. expect(() => comp.detectChanges()).toThrowError( /Attempted to set attribute `dynamic` on a container node. Host bindings are not valid on ng-container or ng-template./, ); }); }); describe('host bindings on edge case properties', () => { it('should handle host bindings with the same name as a primitive value', () => { @Directive({ selector: '[dir]', host: { '[class.a]': 'true', '[class.b]': 'false', }, standalone: false, }) class MyDirective { @HostBinding('class.c') true: any; @HostBinding('class.d') false: any; } @Component({ template: '<span dir></span>', standalone: false, }) class MyApp { @ViewChild(MyDirective) dir!: MyDirective; } TestBed.configureTestingModule({declarations: [MyApp, MyDirective]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const span = fixture.nativeElement.querySelector('span'); expect(span.className).toBe('a'); fixture.componentInstance.dir.true = 1; fixture.componentInstance.dir.false = 2; fixture.detectChanges(); expect(span.className).toBe('a c d'); }); it('should handle host bindings with quoted names', () => { @Directive({ selector: '[dir]', standalone: false, }) class MyDirective { @HostBinding('class.a') 'is-a': any; @HostBinding('class.b') 'is-"b"': any = true; @HostBinding('class.c') '"is-c"': any; } @Component({ template: '<span dir></span>', standalone: false, }) class MyApp { @ViewChild(MyDirective) dir!: MyDirective; } TestBed.configureTestingModule({declarations: [MyApp, MyDirective]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const span = fixture.nativeElement.querySelector('span'); expect(span.className).toBe('b'); fixture.componentInstance.dir['is-a'] = 1; fixture.componentInstance.dir['"is-c"'] = 2; fixture.detectChanges(); expect(span.className).toBe('b a c'); }); }); });
{ "end_byte": 52485, "start_byte": 48576, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_binding_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_0_1398
/** * @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 */ // Make the `$localize()` global function available to the compiled templates, and the direct calls // below. This would normally be done inside the application `polyfills.ts` file. import '@angular/localize/init'; import {CommonModule, DOCUMENT, registerLocaleData} from '@angular/common'; import localeEs from '@angular/common/locales/es'; import localeRo from '@angular/common/locales/ro'; import {computeMsgId} from '@angular/compiler'; import { Attribute, Component, ContentChild, ContentChildren, Directive, ElementRef, HostBinding, Input, LOCALE_ID, NO_ERRORS_SCHEMA, Pipe, PipeTransform, QueryList, TemplateRef, Type, ViewChild, ViewContainerRef, ɵsetDocument, } from '@angular/core'; import {HEADER_OFFSET} from '@angular/core/src/render3/interfaces/view'; import {getComponentLView} from '@angular/core/src/render3/util/discovery_utils'; import {DeferBlockBehavior, DeferBlockState, TestBed} from '@angular/core/testing'; import {clearTranslations, loadTranslations} from '@angular/localize'; import {By} from '@angular/platform-browser'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {BehaviorSubject} from 'rxjs';
{ "end_byte": 1398, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_1400_8518
escribe('runtime i18n', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [AppComp, DirectiveWithTplRef, UppercasePipe], // In some of the tests we use made-up tag names for better readability, however // they'll cause validation errors. Add the `NO_ERRORS_SCHEMA` so that we don't have // to declare dummy components for each one of them. schemas: [NO_ERRORS_SCHEMA], }); }); afterEach(() => { clearTranslations(); }); it('should translate text', () => { loadTranslations({[computeMsgId('text')]: 'texte'}); const fixture = initWithTemplate(AppComp, `<div i18n>text</div>`); expect(fixture.nativeElement.innerHTML).toEqual(`<div>texte</div>`); }); it('should support interpolations', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}!')]: 'Bonjour {$INTERPOLATION}!'}); const fixture = initWithTemplate(AppComp, `<div i18n>Hello {{name}}!</div>`); expect(fixture.nativeElement.innerHTML).toEqual(`<div>Bonjour Angular!</div>`); fixture.componentRef.instance.name = `John`; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`<div>Bonjour John!</div>`); }); it('should support named interpolations', () => { loadTranslations({ [computeMsgId(' Hello {$USER_NAME}! Emails: {$AMOUNT_OF_EMAILS_RECEIVED} ')]: ' Bonjour {$USER_NAME}! Emails: {$AMOUNT_OF_EMAILS_RECEIVED} ', }); const fixture = initWithTemplate( AppComp, ` <div i18n> Hello {{ name // i18n(ph="user_name") }}! Emails: {{ count // i18n(ph="amount of emails received") }} </div> `, ); expect(fixture.nativeElement.innerHTML).toEqual(`<div> Bonjour Angular! Emails: 0 </div>`); fixture.componentRef.instance.name = `John`; fixture.componentRef.instance.count = 5; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`<div> Bonjour John! Emails: 5 </div>`); }); it('should support named interpolations with the same name', () => { loadTranslations({ [computeMsgId(' Hello {$PH_NAME} {$PH_NAME_1}! ')]: ' Bonjour {$PH_NAME} {$PH_NAME_1}! ', }); const fixture = initWithTemplate( AppComp, ` <div i18n> Hello {{ name // i18n(ph="ph_name") }} {{ description // i18n(ph="ph_name") }}! </div> `, ); expect(fixture.nativeElement.innerHTML).toEqual(`<div> Bonjour Angular Web Framework! </div>`); fixture.componentRef.instance.name = 'Other'; fixture.componentRef.instance.description = 'Backend Framework'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div> Bonjour Other Backend Framework! </div>`, ); }); it('should support interpolations with custom interpolation config', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); const interpolation = ['{%', '%}'] as [string, string]; TestBed.overrideComponent(AppComp, {set: {interpolation}}); const fixture = initWithTemplate(AppComp, `<div i18n>Hello {% name %}</div>`); expect(fixture.nativeElement.innerHTML).toBe('<div>Bonjour Angular</div>'); }); it('should support &ngsp; in translatable sections', () => { // note: the `` unicode symbol represents the `&ngsp;` in translations loadTranslations({[computeMsgId('text ||')]: 'texte ||'}); const fixture = initWithTemplate(AppCompWithWhitespaces, `<div i18n>text |&ngsp;|</div>`); expect(fixture.nativeElement.innerHTML).toEqual(`<div>texte | |</div>`); }); it('should support interpolations with complex expressions', () => { loadTranslations({ [computeMsgId(' {$INTERPOLATION} - {$INTERPOLATION_1} - {$INTERPOLATION_2} ')]: ' {$INTERPOLATION} - {$INTERPOLATION_1} - {$INTERPOLATION_2} (fr) ', }); const fixture = initWithTemplate( AppComp, ` <div i18n> {{ name | uppercase }} - {{ obj?.a?.b }} - {{ obj?.getA()?.b }} </div> `, ); // the `obj` field is not yet defined, so 2nd and 3rd interpolations return empty // strings expect(fixture.nativeElement.innerHTML).toEqual(`<div> ANGULAR - - (fr) </div>`); fixture.componentRef.instance.obj = { a: {b: 'value 1'}, getA: () => ({b: 'value 2'}), }; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div> ANGULAR - value 1 - value 2 (fr) </div>`, ); }); it('should support elements', () => { loadTranslations({ [computeMsgId( 'Hello {$START_TAG_SPAN}world{$CLOSE_TAG_SPAN} and {$START_TAG_DIV}universe{$CLOSE_TAG_DIV}!', '', )]: 'Bonjour {$START_TAG_SPAN}monde{$CLOSE_TAG_SPAN} et {$START_TAG_DIV}univers{$CLOSE_TAG_DIV}!', }); const fixture = initWithTemplate( AppComp, `<div i18n>Hello <span>world</span> and <div>universe</div>!</div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div>Bonjour <span>monde</span> et <div>univers</div>!</div>`, ); }); it('should support removing elements', () => { loadTranslations({ [computeMsgId( 'Hello {$START_BOLD_TEXT}my{$CLOSE_BOLD_TEXT}{$START_TAG_SPAN}world{$CLOSE_TAG_SPAN}', '', )]: 'Bonjour {$START_TAG_SPAN}monde{$CLOSE_TAG_SPAN}', }); const fixture = initWithTemplate( AppComp, `<div i18n>Hello <b>my</b><span>world</span></div><div>!</div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div>Bonjour <span>monde</span></div><div>!</div>`, ); }); it('should support moving elements', () => { loadTranslations({ [computeMsgId( 'Hello {$START_TAG_SPAN}world{$CLOSE_TAG_SPAN} and {$START_TAG_DIV}universe{$CLOSE_TAG_DIV}!', '', )]: 'Bonjour {$START_TAG_DIV}univers{$CLOSE_TAG_DIV} et {$START_TAG_SPAN}monde{$CLOSE_TAG_SPAN}!', }); const fixture = initWithTemplate( AppComp, `<div i18n>Hello <span>world</span> and <div>universe</div>!</div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div>Bonjour <div>univers</div> et <span>monde</span>!</div>`, ); }); it('should support template directives', () => { loadTranslations({ [computeMsgId( 'Content: {$START_TAG_DIV}before{$START_TAG_SPAN}middle{$CLOSE_TAG_SPAN}after{$CLOSE_TAG_DIV}!', '', )]: 'Contenu: {$START_TAG_DIV}avant{$START_TAG_SPAN}milieu{$CLOSE_TAG_SPAN}après{$CLOSE_TAG_DIV}!', }); const fixture = initWithTemplate( AppComp, `<div i18n>Content: <div *ngIf="visible">before<span>middle</span>after</div>!</div>`, ); expect(fixture.nativeElement.innerHTML) .toEqual(`<div>Contenu: <div>avant<span>milieu</span>après</div><!--bindings={ "ng-reflect-ng-if": "true" }-->!</div>`); fixture.componentRef.instance.visible = false; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`<div>Contenu: <!--bindings={ "ng-reflect-ng-if": "false" }-->!</div>`); }); it('s
{ "end_byte": 8518, "start_byte": 1400, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_8522_15214
d support multiple i18n blocks', () => { loadTranslations({ [computeMsgId('trad {$INTERPOLATION}')]: 'traduction {$INTERPOLATION}', [computeMsgId('start {$INTERPOLATION} middle {$INTERPOLATION_1} end')]: 'start {$INTERPOLATION_1} middle {$INTERPOLATION} end', [computeMsgId( '{$START_TAG_C}trad{$CLOSE_TAG_C}{$START_TAG_D}{$CLOSE_TAG_D}{$START_TAG_E}{$CLOSE_TAG_E}', '', )]: '{$START_TAG_E}{$CLOSE_TAG_E}{$START_TAG_C}traduction{$CLOSE_TAG_C}', }); const fixture = initWithTemplate( AppComp, ` <div> <a i18n>trad {{name}}</a> hello <b i18n i18n-title title="start {{count}} middle {{name}} end"> <c>trad</c> <d></d> <e></e> </b> </div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div><a>traduction Angular</a> hello <b title="start Angular middle 0 end"><e></e><c>traduction</c></b></div>`, ); }); it('should support multiple sibling i18n blocks', () => { loadTranslations({ [computeMsgId('Section 1')]: 'Section un', [computeMsgId('Section 2')]: 'Section deux', [computeMsgId('Section 3')]: 'Section trois', }); const fixture = initWithTemplate( AppComp, ` <div> <div i18n>Section 1</div> <div i18n>Section 2</div> <div i18n>Section 3</div> </div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div><div>Section un</div><div>Section deux</div><div>Section trois</div></div>`, ); }); it('should support multiple sibling i18n blocks inside of a template directive', () => { loadTranslations({ [computeMsgId('Section 1')]: 'Section un', [computeMsgId('Section 2')]: 'Section deux', [computeMsgId('Section 3')]: 'Section trois', }); const fixture = initWithTemplate( AppComp, ` <ul *ngFor="let item of [1,2,3]"> <li i18n>Section 1</li> <li i18n>Section 2</li> <li i18n>Section 3</li> </ul>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<ul><li>Section un</li><li>Section deux</li><li>Section trois</li></ul><ul><li>Section un</li><li>Section deux</li><li>Section trois</li></ul><ul><li>Section un</li><li>Section deux</li><li>Section trois</li></ul><!--bindings={ "ng-reflect-ng-for-of": "1,2,3" }-->`, ); }); it('should properly escape quotes in content', () => { loadTranslations({ [computeMsgId('\'Single quotes\' and "Double quotes"')]: '\'Guillemets simples\' et "Guillemets doubles"', }); const fixture = initWithTemplate( AppComp, `<div i18n>'Single quotes' and "Double quotes"</div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( '<div>\'Guillemets simples\' et "Guillemets doubles"</div>', ); }); it('should correctly bind to context in nested template', () => { loadTranslations({[computeMsgId('Item {$INTERPOLATION}')]: 'Article {$INTERPOLATION}'}); const fixture = initWithTemplate( AppComp, ` <div *ngFor='let id of items'> <div i18n>Item {{ id }}</div> </div> `, ); const element = fixture.nativeElement; for (let i = 0; i < element.children.length; i++) { const child = element.children[i]; expect(child).toHaveText(`Article ${i + 1}`); } }); it('should ignore i18n attributes on self-closing tags', () => { const fixture = initWithTemplate(AppComp, '<img src="logo.png" i18n>'); expect(fixture.nativeElement.innerHTML).toBe(`<img src="logo.png">`); }); it('should handle i18n attribute with directives', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); const fixture = initWithTemplate(AppComp, `<div *ngIf="visible" i18n>Hello {{ name }}</div>`); expect(fixture.nativeElement.firstChild).toHaveText('Bonjour Angular'); }); it('should work correctly with event listeners', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); @Component({ selector: 'app-comp', template: `<div i18n (click)="onClick()">Hello {{ name }}</div>`, standalone: false, }) class ListenerComp { name = `Angular`; clicks = 0; onClick() { this.clicks++; } } TestBed.configureTestingModule({declarations: [ListenerComp]}); const fixture = TestBed.createComponent(ListenerComp); fixture.detectChanges(); const element = fixture.nativeElement.firstChild; const instance = fixture.componentInstance; expect(element).toHaveText('Bonjour Angular'); expect(instance.clicks).toBe(0); element.click(); expect(instance.clicks).toBe(1); }); it('should support local refs inside i18n block', () => { loadTranslations({ [computeMsgId( '{$START_TAG_NG_CONTAINER} One {$CLOSE_TAG_NG_CONTAINER}' + '{$START_TAG_DIV} Two {$CLOSE_TAG_DIV}' + '{$START_TAG_SPAN} Three {$CLOSE_TAG_SPAN}' + '{$START_TAG_NG_TEMPLATE} Four {$CLOSE_TAG_NG_TEMPLATE}' + '{$START_TAG_NG_CONTAINER_1}{$CLOSE_TAG_NG_CONTAINER}', )]: '{$START_TAG_NG_CONTAINER} Une {$CLOSE_TAG_NG_CONTAINER}' + '{$START_TAG_DIV} Deux {$CLOSE_TAG_DIV}' + '{$START_TAG_SPAN} Trois {$CLOSE_TAG_SPAN}' + '{$START_TAG_NG_TEMPLATE} Quatre {$CLOSE_TAG_NG_TEMPLATE}' + '{$START_TAG_NG_CONTAINER_1}{$CLOSE_TAG_NG_CONTAINER}', }); const fixture = initWithTemplate( AppComp, ` <div i18n> <ng-container #localRefA> One </ng-container> <div #localRefB> Two </div> <span #localRefC> Three </span> <ng-template #localRefD> Four </ng-template> <ng-container *ngTemplateOutlet="localRefD"></ng-container> </div> `, ); expect(fixture.nativeElement.textContent).toBe(' Une Deux Trois Quatre '); }); it('should handle local refs correctly in case an element is removed in translation', () => { loadTranslations({ [computeMsgId( '{$START_TAG_NG_CONTAINER} One {$CLOSE_TAG_NG_CONTAINER}' + '{$START_TAG_DIV} Two {$CLOSE_TAG_DIV}' + '{$START_TAG_SPAN} Three {$CLOSE_TAG_SPAN}', )]: '{$START_TAG_DIV} Deux {$CLOSE_TAG_DIV}', }); const fixture = initWithTemplate( AppComp, ` <div i18n> <ng-container #localRefA> One </ng-container> <div #localRefB> Two </div> <span #localRefC> Three </span> </div> `, ); expect(fixture.nativeElement.textContent).toBe(' Deux '); }); it('s
{ "end_byte": 15214, "start_byte": 8522, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_15218_21802
d support conditional blocks', () => { loadTranslations({ [computeMsgId( 'Content: {$START_BLOCK_IF}before{$START_TAG_SPAN}zero{$CLOSE_TAG_SPAN}after' + '{$CLOSE_BLOCK_IF}{$START_BLOCK_ELSE_IF}before{$START_TAG_DIV}one{$CLOSE_TAG_DIV}' + 'after{$CLOSE_BLOCK_ELSE_IF}{$START_BLOCK_ELSE}before{$START_TAG_BUTTON}' + 'otherwise{$CLOSE_TAG_BUTTON}after{$CLOSE_BLOCK_ELSE}!', '', )]: 'Contenido: {$START_BLOCK_IF}antes{$START_TAG_SPAN}cero{$CLOSE_TAG_SPAN}después' + '{$CLOSE_BLOCK_IF}{$START_BLOCK_ELSE_IF}antes{$START_TAG_DIV}uno{$CLOSE_TAG_DIV}' + 'después{$CLOSE_BLOCK_ELSE_IF}{$START_BLOCK_ELSE}antes{$START_TAG_BUTTON}' + 'si no{$CLOSE_TAG_BUTTON}después{$CLOSE_BLOCK_ELSE}!', }); const fixture = initWithTemplate( AppComp, '<div i18n>Content: @if (count === 0) {before<span>zero</span>after} ' + '@else if (count === 1) {before<div>one</div>after} ' + '@else {before<button>otherwise</button>after}!</div>', ); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: antes<span>cero</span>después<!--container--><!--container-->' + '<!--container-->!</div>', ); fixture.componentInstance.count = 1; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: <!--container-->antes<div>uno</div>después<!--container-->' + '<!--container-->!</div>', ); fixture.componentInstance.count = 2; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: <!--container--><!--container-->antes<button>si no</button>después' + '<!--container-->!</div>', ); }); it('should support switch blocks', () => { loadTranslations({ [computeMsgId( 'Content: {$START_BLOCK_CASE}before{$START_TAG_SPAN}zero{$CLOSE_TAG_SPAN}after' + '{$CLOSE_BLOCK_CASE}{$START_BLOCK_CASE_1}before{$START_TAG_DIV}one' + '{$CLOSE_TAG_DIV}after{$CLOSE_BLOCK_CASE}{$START_BLOCK_DEFAULT}before' + '{$START_TAG_BUTTON}otherwise{$CLOSE_TAG_BUTTON}after{$CLOSE_BLOCK_DEFAULT}', '', )]: 'Contenido: {$START_BLOCK_CASE}antes{$START_TAG_SPAN}cero{$CLOSE_TAG_SPAN}después' + '{$CLOSE_BLOCK_CASE}{$START_BLOCK_CASE_1}antes{$START_TAG_DIV}uno' + '{$CLOSE_TAG_DIV}después{$CLOSE_BLOCK_CASE}{$START_BLOCK_DEFAULT}antes' + '{$START_TAG_BUTTON}si no{$CLOSE_TAG_BUTTON}después{$CLOSE_BLOCK_DEFAULT}', }); const fixture = initWithTemplate( AppComp, '<div i18n>Content: @switch (count) {' + '@case (0) {before<span>zero</span>after}' + '@case (1) {before<div>one</div>after}' + '@default {before<button>otherwise</button>after}' + '}</div>', ); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: antes<span>cero</span>después<!--container--><!--container-->' + '<!--container--></div>', ); fixture.componentInstance.count = 1; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: <!--container-->antes<div>uno</div>después<!--container-->' + '<!--container--></div>', ); fixture.componentInstance.count = 2; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: <!--container--><!--container-->antes<button>si no</button>después' + '<!--container--></div>', ); }); it('should support for loop blocks', () => { loadTranslations({ [computeMsgId( 'Content: {$START_BLOCK_FOR}before{$START_TAG_SPAN}' + 'middle{$CLOSE_TAG_SPAN}after{$CLOSE_BLOCK_FOR}{$START_BLOCK_EMPTY}' + 'before{$START_TAG_DIV}empty{$CLOSE_TAG_DIV}after{$CLOSE_BLOCK_EMPTY}!', )]: 'Contenido: {$START_BLOCK_FOR}antes{$START_TAG_SPAN}' + 'medio{$CLOSE_TAG_SPAN}después{$CLOSE_BLOCK_FOR}{$START_BLOCK_EMPTY}' + 'antes{$START_TAG_DIV}vacío{$CLOSE_TAG_DIV}después{$CLOSE_BLOCK_EMPTY}!', }); const fixture = initWithTemplate( AppComp, '<div i18n>Content: @for (item of items; track item) {before<span>middle</span>after}' + '@empty {before<div>empty</div>after}!</div>', ); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: antes<span>medio</span>' + 'despuésantes<span>medio</span>despuésantes<span>medio</span>' + 'después<!--container--><!--container-->!</div>', ); fixture.componentInstance.items = []; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: <!--container-->antes<div>' + 'vacío</div>después<!--container-->!</div>', ); }); it('should support deferred blocks', async () => { loadTranslations({ [computeMsgId( 'Content: {$START_BLOCK_DEFER}before{$START_TAG_SPAN}middle' + '{$CLOSE_TAG_SPAN}after{$CLOSE_BLOCK_DEFER}{$START_BLOCK_PLACEHOLDER}before' + '{$START_TAG_DIV}placeholder{$CLOSE_TAG_DIV}after{$CLOSE_BLOCK_PLACEHOLDER}!', '', )]: 'Contenido: {$START_BLOCK_DEFER}before{$START_TAG_SPAN}medio' + '{$CLOSE_TAG_SPAN}after{$CLOSE_BLOCK_DEFER}{$START_BLOCK_PLACEHOLDER}before' + '{$START_TAG_DIV}marcador de posición{$CLOSE_TAG_DIV}after{$CLOSE_BLOCK_PLACEHOLDER}!', }); @Component({ selector: 'defer-comp', standalone: true, template: '<div i18n>Content: @defer (when isLoaded) {before<span>middle</span>after} ' + '@placeholder {before<div>placeholder</div>after}!</div>', }) class DeferComp { isLoaded = false; } TestBed.configureTestingModule({ imports: [DeferComp], deferBlockBehavior: DeferBlockBehavior.Manual, teardown: {destroyAfterEach: true}, }); const fixture = TestBed.createComponent(DeferComp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: <!--container-->' + '<!--container-->!before<div>marcador de posición</div>after<!--container--></div>', ); const deferBlock = (await fixture.getDeferBlocks())[0]; fixture.componentInstance.isLoaded = true; fixture.detectChanges(); await deferBlock.render(DeferBlockState.Complete); expect(fixture.nativeElement.innerHTML).toEqual( '<div>Contenido: <!--container-->' + '<!--container-->!before<span>medio</span>after<!--container--></div>', ); }); describe('ng-container and
{ "end_byte": 21802, "start_byte": 15218, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_21806_29247
emplate support', () => { it('should support ng-container', () => { loadTranslations({[computeMsgId('text')]: 'texte'}); const fixture = initWithTemplate(AppComp, `<ng-container i18n>text</ng-container>`); expect(fixture.nativeElement.innerHTML).toEqual(`texte<!--ng-container-->`); }); it('should handle single translation message within ng-template', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); const fixture = initWithTemplate( AppComp, `<ng-template i18n tplRef>Hello {{ name }}</ng-template>`, ); const element = fixture.nativeElement; expect(element).toHaveText('Bonjour Angular'); }); // Note: applying structural directives to <ng-template> is typically user error, but it // is technically allowed, so we need to support it. it('should handle structural directives on ng-template', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); const fixture = initWithTemplate( AppComp, `<ng-template *ngIf="name" i18n tplRef>Hello {{ name }}</ng-template>`, ); const element = fixture.nativeElement; expect(element).toHaveText('Bonjour Angular'); }); it('should be able to act as child elements inside i18n block (plain text content)', () => { loadTranslations({ [computeMsgId( '{$START_TAG_NG_TEMPLATE} Hello {$CLOSE_TAG_NG_TEMPLATE}{$START_TAG_NG_CONTAINER} Bye {$CLOSE_TAG_NG_CONTAINER}', '', )]: '{$START_TAG_NG_TEMPLATE} Bonjour {$CLOSE_TAG_NG_TEMPLATE}{$START_TAG_NG_CONTAINER} Au revoir {$CLOSE_TAG_NG_CONTAINER}', }); const fixture = initWithTemplate( AppComp, ` <div i18n> <ng-template tplRef> Hello </ng-template> <ng-container> Bye </ng-container> </div> `, ); const element = fixture.nativeElement.firstChild; expect(element.textContent.replace(/\s+/g, ' ').trim()).toBe('Bonjour Au revoir'); }); it('should be able to act as child elements inside i18n block (text + tags)', () => { loadTranslations({ [computeMsgId( '{$START_TAG_NG_TEMPLATE}{$START_TAG_SPAN}Hello{$CLOSE_TAG_SPAN}{$CLOSE_TAG_NG_TEMPLATE}{$START_TAG_NG_CONTAINER}{$START_TAG_SPAN}Hello{$CLOSE_TAG_SPAN}{$CLOSE_TAG_NG_CONTAINER}', '', )]: '{$START_TAG_NG_TEMPLATE}{$START_TAG_SPAN}Bonjour{$CLOSE_TAG_SPAN}{$CLOSE_TAG_NG_TEMPLATE}{$START_TAG_NG_CONTAINER}{$START_TAG_SPAN}Bonjour{$CLOSE_TAG_SPAN}{$CLOSE_TAG_NG_CONTAINER}', }); const fixture = initWithTemplate( AppComp, ` <div i18n> <ng-template tplRef> <span>Hello</span> </ng-template> <ng-container> <span>Hello</span> </ng-container> </div> `, ); const element = fixture.nativeElement; const spans = element.getElementsByTagName('span'); for (let i = 0; i < spans.length; i++) { expect(spans[i]).toHaveText('Bonjour'); } }); it('should be able to act as child elements inside i18n block (text + pipes)', () => { loadTranslations({ [computeMsgId( '{$START_TAG_NG_TEMPLATE}Hello {$INTERPOLATION}{$CLOSE_TAG_NG_TEMPLATE}{$START_TAG_NG_CONTAINER}Bye {$INTERPOLATION}{$CLOSE_TAG_NG_CONTAINER}', '', )]: '{$START_TAG_NG_TEMPLATE}Hej {$INTERPOLATION}{$CLOSE_TAG_NG_TEMPLATE}{$START_TAG_NG_CONTAINER}Vi ses {$INTERPOLATION}{$CLOSE_TAG_NG_CONTAINER}', }); const fixture = initWithTemplate( AppComp, ` <div i18n> <ng-template tplRef>Hello {{name | uppercase}}</ng-template> <ng-container>Bye {{name | uppercase}}</ng-container> </div> `, ); const element = fixture.nativeElement.firstChild; expect(element.textContent.replace(/\s+/g, ' ').trim()).toBe('Hej ANGULARVi ses ANGULAR'); }); it('should be able to handle deep nested levels with templates', () => { loadTranslations({ [computeMsgId( '{$START_TAG_SPAN} Hello - 1 {$CLOSE_TAG_SPAN}{$START_TAG_SPAN_1} Hello - 2 {$START_TAG_SPAN_1} Hello - 3 {$START_TAG_SPAN_1} Hello - 4 {$CLOSE_TAG_SPAN}{$CLOSE_TAG_SPAN}{$CLOSE_TAG_SPAN}{$START_TAG_SPAN} Hello - 5 {$CLOSE_TAG_SPAN}', '', )]: '{$START_TAG_SPAN} Bonjour - 1 {$CLOSE_TAG_SPAN}{$START_TAG_SPAN_1} Bonjour - 2 {$START_TAG_SPAN_1} Bonjour - 3 {$START_TAG_SPAN_1} Bonjour - 4 {$CLOSE_TAG_SPAN}{$CLOSE_TAG_SPAN}{$CLOSE_TAG_SPAN}{$START_TAG_SPAN} Bonjour - 5 {$CLOSE_TAG_SPAN}', }); const fixture = initWithTemplate( AppComp, ` <div i18n> <span> Hello - 1 </span> <span *ngIf="visible"> Hello - 2 <span *ngIf="visible"> Hello - 3 <span *ngIf="visible"> Hello - 4 </span> </span> </span> <span> Hello - 5 </span> </div> `, ); const element = fixture.nativeElement; const spans = element.getElementsByTagName('span'); for (let i = 0; i < spans.length; i++) { expect(spans[i].innerHTML).toContain(`Bonjour - ${i + 1}`); } }); it('should handle self-closing tags as content', () => { loadTranslations({ [computeMsgId('{$START_TAG_SPAN}My logo{$TAG_IMG}{$CLOSE_TAG_SPAN}')]: '{$START_TAG_SPAN}Mon logo{$TAG_IMG}{$CLOSE_TAG_SPAN}', }); const content = `My logo<img src="logo.png" title="Logo">`; const fixture = initWithTemplate( AppComp, ` <ng-container i18n> <span>${content}</span> </ng-container> <ng-template i18n tplRef> <span>${content}</span> </ng-template> `, ); const element = fixture.nativeElement; const spans = element.getElementsByTagName('span'); for (let i = 0; i < spans.length; i++) { const child = spans[i]; expect(child).toHaveText('Mon logo'); } }); it('should correctly find context for an element inside i18n section in <ng-template>', () => { loadTranslations({ [computeMsgId('{$START_LINK}Not logged in{$CLOSE_LINK}')]: '{$START_LINK}Not logged in{$CLOSE_LINK}', }); @Directive({ selector: '[myDir]', standalone: false, }) class Dir { condition = true; } @Component({ selector: 'my-cmp', template: ` <div *ngIf="isLogged; else notLoggedIn"> <span>Logged in</span> </div> <ng-template #notLoggedIn i18n> <a myDir>Not logged in</a> </ng-template> `, standalone: false, }) class Cmp { isLogged = false; } TestBed.configureTestingModule({ declarations: [Cmp, Dir], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const a = fixture.debugElement.query(By.css('a')); const dir = a.injector.get(Dir); expect(dir.condition).toEqual(true); }); }); describe('should work corre
{ "end_byte": 29247, "start_byte": 21806, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_29251_33846
with namespaces', () => { beforeEach(() => { function _document(): any { // Tell Ivy about the global document ɵsetDocument(document); return document; } TestBed.configureTestingModule({ providers: [{provide: DOCUMENT, useFactory: _document, deps: []}], }); }); it('should handle namespaces inside i18n blocks', () => { loadTranslations({ [computeMsgId( '{$START_TAG__XHTML_DIV} Hello ' + '{$START_TAG__XHTML_SPAN}world{$CLOSE_TAG__XHTML_SPAN}{$CLOSE_TAG__XHTML_DIV}', )]: '{$START_TAG__XHTML_DIV} Bonjour ' + '{$START_TAG__XHTML_SPAN}monde{$CLOSE_TAG__XHTML_SPAN}{$CLOSE_TAG__XHTML_DIV}', }); const fixture = initWithTemplate( AppComp, ` <svg xmlns="http://www.w3.org/2000/svg"> <foreignObject i18n> <xhtml:div xmlns="http://www.w3.org/1999/xhtml"> Hello <span>world</span> </xhtml:div> </foreignObject> </svg> `, ); const element = fixture.nativeElement; expect(element.textContent.trim()).toBe('Bonjour monde'); expect(element.querySelector('svg').namespaceURI).toBe('http://www.w3.org/2000/svg'); expect(element.querySelector('div').namespaceURI).toBe('http://www.w3.org/1999/xhtml'); expect(element.querySelector('span').namespaceURI).toBe('http://www.w3.org/1999/xhtml'); }); it('should handle namespaces on i18n block containers', () => { loadTranslations({ [computeMsgId(' Hello {$START_TAG__XHTML_SPAN}world{$CLOSE_TAG__XHTML_SPAN}')]: ' Bonjour {$START_TAG__XHTML_SPAN}monde{$CLOSE_TAG__XHTML_SPAN}', }); const fixture = initWithTemplate( AppComp, ` <svg xmlns="http://www.w3.org/2000/svg"> <foreignObject> <xhtml:div xmlns="http://www.w3.org/1999/xhtml" i18n> Hello <span>world</span> </xhtml:div> </foreignObject> </svg> `, ); const element = fixture.nativeElement; expect(element.textContent.trim()).toBe('Bonjour monde'); expect(element.querySelector('svg').namespaceURI).toBe('http://www.w3.org/2000/svg'); expect(element.querySelector('div').namespaceURI).toBe('http://www.w3.org/1999/xhtml'); expect(element.querySelector('span').namespaceURI).toBe('http://www.w3.org/1999/xhtml'); }); }); describe('dynamic TNodes', () => { // When translation occurs the i18n system needs to create dynamic TNodes for the text // nodes so that they can be correctly processed by the `addRemoveViewFromContainer`. describe('ICU', () => { // In the case of ICUs we can't create TNodes for each ICU part, as different ICU // instances may have different selections active and hence have different shape. In // such a case a single `TIcuContainerNode` should be generated only. it('should create a single dynamic TNode for ICU', () => { const fixture = initWithTemplate( AppComp, ` {count, plural, =0 {just now} =1 {one minute ago} other {{{count}} minutes ago} } `.trim(), ); const lView = getComponentLView(fixture.componentInstance); fixture.detectChanges(); expect((fixture.nativeElement as Element).textContent).toEqual('just now'); // We want to ensure that the ICU container does not have any content! // This is because the content is instance dependent and therefore can't be shared // across `TNode`s. expect(fixture.nativeElement.innerHTML).toEqual( `just now<!--ICU ${HEADER_OFFSET + 0}:0-->`, ); }); it('should support multiple ICUs', () => { const fixture = initWithTemplate( AppComp, ` {count, plural, =0 {just now} =1 {one minute ago} other {{{count}} minutes ago} } {name, select, Angular {Mr. Angular} other {Sir} } `, ); // We want to ensure that the ICU container does not have any content! // This is because the content is instance dependent and therefore can't be shared // across `TNode`s. expect(fixture.nativeElement.innerHTML).toEqual( `just now<!--ICU ${HEADER_OFFSET + 0}:0-->Mr. Angular<!--ICU ${HEADER_OFFSET + 1}:0-->`, ); }); }); }); describe('should support ICU
{ "end_byte": 33846, "start_byte": 29251, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_33850_39191
ressions', () => { it('with no root node', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {ten} 20 {twenty} other {other}}')]: '{VAR_SELECT, select, 10 {dix} 20 {vingt} other {autre}}', }); const fixture = initWithTemplate( AppComp, `{count, select, 10 {ten} 20 {twenty} other {other}}`, ); const element = fixture.nativeElement; expect(element).toHaveText('autre'); }); it('with no root node and text surrounding ICU', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {Ten} 20 {Twenty} other {Other}}')]: '{VAR_SELECT, select, 10 {Dix} 20 {Vingt} other {Autre}}', }); const fixture = initWithTemplate( AppComp, ` ICU start --> {count, select, 10 {Ten} 20 {Twenty} other {Other}} <-- ICU end `, ); const element = fixture.nativeElement; expect(element.textContent).toContain('ICU start --> Autre <-- ICU end'); }); it('when `select` or `plural` keywords have spaces after them', () => { loadTranslations({ [computeMsgId('{VAR_SELECT , select , 10 {ten} 20 {twenty} other {other}}')]: '{VAR_SELECT , select , 10 {dix} 20 {vingt} other {autre}}', [computeMsgId('{VAR_PLURAL , plural , =0 {zero} =1 {one} other {other}}')]: '{VAR_PLURAL , plural , =0 {zéro} =1 {une} other {autre}}', }); const fixture = initWithTemplate( AppComp, ` <div i18n> {count, select , 10 {ten} 20 {twenty} other {other}} - {count, plural , =0 {zero} =1 {one} other {other}} </div> `, ); const element = fixture.nativeElement; expect(element.textContent).toContain('autre - zéro'); }); it('with no root node and text and DOM nodes surrounding ICU', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {Ten} 20 {Twenty} other {Other}}')]: '{VAR_SELECT, select, 10 {Dix} 20 {Vingt} other {Autre}}', }); const fixture = initWithTemplate( AppComp, ` <span>ICU start --> </span> {count, select, 10 {Ten} 20 {Twenty} other {Other}} <-- ICU end `, ); const element = fixture.nativeElement; expect(element.textContent).toContain('ICU start --> Autre <-- ICU end'); }); it('with no i18n tag', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {ten} 20 {twenty} other {other}}')]: '{VAR_SELECT, select, 10 {dix} 20 {vingt} other {autre}}', }); const fixture = initWithTemplate( AppComp, `<div>{count, select, 10 {ten} 20 {twenty} other {other}}</div>`, ); const element = fixture.nativeElement; expect(element).toHaveText('autre'); }); it('multiple', () => { loadTranslations({ [computeMsgId( '{VAR_PLURAL, plural, =0 {no {START_BOLD_TEXT}emails{CLOSE_BOLD_TEXT}!} =1 {one {START_ITALIC_TEXT}email{CLOSE_ITALIC_TEXT}} other {{INTERPOLATION} {START_TAG_SPAN}emails{CLOSE_TAG_SPAN}}}', '', )]: '{VAR_PLURAL, plural, =0 {aucun {START_BOLD_TEXT}email{CLOSE_BOLD_TEXT}!} =1 {un {START_ITALIC_TEXT}email{CLOSE_ITALIC_TEXT}} other {{INTERPOLATION} {START_TAG_SPAN}emails{CLOSE_TAG_SPAN}}}', [computeMsgId('{VAR_SELECT, select, other {({INTERPOLATION})}}')]: '{VAR_SELECT, select, other {({INTERPOLATION})}}', [computeMsgId('{$ICU} - {$ICU_1}')]: '{$ICU} - {$ICU_1}', }); const fixture = initWithTemplate( AppComp, `<div i18n>{count, plural, =0 {no <b>emails</b>!} =1 {one <i>email</i>} other {{{count}} <span title="{{name}}">emails</span>} } - {name, select, other {({{name}})} }</div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div>aucun <b>email</b>!<!--ICU ${HEADER_OFFSET + 1}:0--> - (Angular)<!--ICU ${ HEADER_OFFSET + 1 }:3--></div>`, ); fixture.componentRef.instance.count = 4; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div>4 <span title="Angular">emails</span><!--ICU ${ HEADER_OFFSET + 1 }:0--> - (Angular)<!--ICU ${HEADER_OFFSET + 1}:3--></div>`, ); fixture.componentRef.instance.count = 0; fixture.componentRef.instance.name = 'John'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div>aucun <b>email</b>!<!--ICU ${HEADER_OFFSET + 1}:0--> - (John)<!--ICU ${ HEADER_OFFSET + 1 }:3--></div>`, ); }); it('with custom interpolation config', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {ten} other {{INTERPOLATION}}}')]: '{VAR_SELECT, select, 10 {dix} other {{INTERPOLATION}}}', }); const interpolation = ['{%', '%}'] as [string, string]; TestBed.overrideComponent(AppComp, {set: {interpolation}}); const fixture = initWithTemplate( AppComp, `<div i18n>{count, select, 10 {ten} other {{% name %}}}</div>`, ); expect(fixture.nativeElement).toHaveText(`Angular`); }); it('inside HTML elements', (
{ "end_byte": 39191, "start_byte": 33850, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_39197_45856
loadTranslations({ [computeMsgId( '{VAR_PLURAL, plural, =0 {no {START_BOLD_TEXT}emails{CLOSE_BOLD_TEXT}!} =1 {one {START_ITALIC_TEXT}email{CLOSE_ITALIC_TEXT}} other {{INTERPOLATION} {START_TAG_SPAN}emails{CLOSE_TAG_SPAN}}}', '', )]: '{VAR_PLURAL, plural, =0 {aucun {START_BOLD_TEXT}email{CLOSE_BOLD_TEXT}!} =1 {un {START_ITALIC_TEXT}email{CLOSE_ITALIC_TEXT}} other {{INTERPOLATION} {START_TAG_SPAN}emails{CLOSE_TAG_SPAN}}}', [computeMsgId('{VAR_SELECT, select, other {({INTERPOLATION})}}')]: '{VAR_SELECT, select, other {({INTERPOLATION})}}', [computeMsgId( '{$START_TAG_SPAN_1}{$ICU}{$CLOSE_TAG_SPAN} - ' + '{$START_TAG_SPAN_1}{$ICU_1}{$CLOSE_TAG_SPAN}', )]: '{$START_TAG_SPAN_1}{$ICU}{$CLOSE_TAG_SPAN} - {$START_TAG_SPAN_1}{$ICU_1}{$CLOSE_TAG_SPAN}', }); const fixture = initWithTemplate( AppComp, `<div i18n><span>{count, plural, =0 {no <b>emails</b>!} =1 {one <i>email</i>} other {{{count}} <span title="{{name}}">emails</span>} }</span> - <span>{name, select, other {({{name}})} }</span></div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div>` + `<span>aucun <b>email</b>!<!--ICU ${HEADER_OFFSET + 1}:0--></span>` + ` - ` + `<span>(Angular)<!--ICU ${HEADER_OFFSET + 1}:3--></span>` + `</div>`, ); fixture.componentRef.instance.count = 4; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div>` + `<span>4 <span title="Angular">emails</span><!--ICU ${HEADER_OFFSET + 1}:0--></span>` + ` - ` + `<span>(Angular)<!--ICU ${HEADER_OFFSET + 1}:3--></span>` + `</div>`, ); fixture.componentRef.instance.count = 0; fixture.componentRef.instance.name = 'John'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div>` + `<span>aucun <b>email</b>!<!--ICU ${HEADER_OFFSET + 1}:0--></span>` + ` - ` + `<span>(John)<!--ICU ${HEADER_OFFSET + 1}:3--></span>` + `</div>`, ); }); it('inside template directives', () => { loadTranslations({ [computeMsgId('{$START_TAG_SPAN}{$ICU}{$CLOSE_TAG_SPAN}')]: '{$START_TAG_SPAN}{$ICU}{$CLOSE_TAG_SPAN}', [computeMsgId('{VAR_SELECT, select, other {({INTERPOLATION})}}')]: '{VAR_SELECT, select, other {({INTERPOLATION})}}', }); const fixture = initWithTemplate( AppComp, `<div i18n><span *ngIf="visible">{name, select, other {({{name}})} }</span></div>`, ); expect(fixture.nativeElement.innerHTML).toEqual(`<div><span>(Angular)<!--ICU ${ HEADER_OFFSET + 0 }:0--></span><!--bindings={ "ng-reflect-ng-if": "true" }--></div>`); fixture.componentRef.instance.visible = false; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`<div><!--bindings={ "ng-reflect-ng-if": "false" }--></div>`); }); it('inside ng-container', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, other {({INTERPOLATION})}}')]: '{VAR_SELECT, select, other {({INTERPOLATION})}}', }); const fixture = initWithTemplate( AppComp, `<ng-container i18n>{name, select, other {({{name}})} }</ng-container>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `(Angular)<!--ICU ${HEADER_OFFSET + 1}:0--><!--ng-container-->`, ); }); it('inside <ng-template>', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {ten} 20 {twenty} other {other}}')]: '{VAR_SELECT, select, 10 {dix} 20 {vingt} other {autre}}', }); const fixture = initWithTemplate( AppComp, ` <ng-template i18n tplRef>` + `{count, select, 10 {ten} 20 {twenty} other {other}}` + `</ng-template> `, ); const element = fixture.nativeElement; expect(element).toHaveText('autre'); }); it('nested', () => { loadTranslations({ [computeMsgId( '{VAR_PLURAL, plural, =0 {zero} other {{INTERPOLATION} {VAR_SELECT, select, cat {cats} dog {dogs} other {animals}}!}}', '', )]: '{VAR_PLURAL, plural, =0 {zero} other {{INTERPOLATION} {VAR_SELECT, select, cat {chats} dog {chiens} other {animaux}}!}}', }); const fixture = initWithTemplate( AppComp, `<div i18n>{count, plural, =0 {zero} other {{{count}} {name, select, cat {cats} dog {dogs} other {animals} }!} }</div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div>zero<!--ICU ${HEADER_OFFSET + 1}:1--></div>`, ); fixture.componentRef.instance.count = 4; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div>4 animaux<!--nested ICU 0-->!<!--ICU ${HEADER_OFFSET + 1}:1--></div>`, ); }); it('nested with interpolations in "other" blocks', () => { loadTranslations({ [computeMsgId( '{VAR_PLURAL, plural, =0 {zero} =2 {{INTERPOLATION} {VAR_SELECT, select, cat {cats} dog {dogs} other {animals}}!} other {other - {INTERPOLATION}}}', '', )]: '{VAR_PLURAL, plural, =0 {zero} =2 {{INTERPOLATION} {VAR_SELECT, select, cat {chats} dog {chiens} other {animaux}}!} other {autre - {INTERPOLATION}}}', }); const fixture = initWithTemplate( AppComp, `<div i18n>{count, plural, =0 {zero} =2 {{{count}} {name, select, cat {cats} dog {dogs} other {animals} }!} other {other - {{count}}} }</div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div>zero<!--ICU ${HEADER_OFFSET + 1}:1--></div>`, ); fixture.componentRef.instance.count = 2; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div>2 animaux<!--nested ICU 0-->!<!--ICU ${HEADER_OFFSET + 1}:1--></div>`, ); fixture.componentRef.instance.count = 4; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div>autre - 4<!--ICU ${HEADER_OFFSET + 1}:1--></div>`, ); }); it('should return the correc
{ "end_byte": 45856, "start_byte": 39197, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_45862_52160
al form for ICU expressions when using "ro" locale', () => { // The "ro" locale has a complex plural function that can handle muliple options // (and string inputs) // // function plural(n: number): number { // let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; // if (i === 1 && v === 0) return 1; // if (!(v === 0) || n === 0 || // !(n === 1) && n % 100 === Math.floor(n % 100) && n % 100 >= 1 && n % 100 <= 19) // return 3; // return 5; // } // // Compare this to the "es" locale in the next test loadTranslations({ [computeMsgId( '{VAR_PLURAL, plural, =0 {no email} =one {one email} =few {a few emails} =other {lots of emails}}', )]: '{VAR_PLURAL, plural, =0 {no email} =one {one email} =few {a few emails} =other {lots of emails}}', }); registerLocaleData(localeRo); TestBed.configureTestingModule({providers: [{provide: LOCALE_ID, useValue: 'ro'}]}); // We could also use `TestBed.overrideProvider(LOCALE_ID, {useValue: 'ro'});` const fixture = initWithTemplate( AppComp, ` {count, plural, =0 {no email} =one {one email} =few {a few emails} =other {lots of emails} }`, ); expect(fixture.nativeElement.innerHTML).toEqual(`no email<!--ICU ${HEADER_OFFSET + 0}:0-->`); // Change detection cycle, no model changes fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`no email<!--ICU ${HEADER_OFFSET + 0}:0-->`); fixture.componentInstance.count = 3; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `a few emails<!--ICU ${HEADER_OFFSET + 0}:0-->`, ); fixture.componentInstance.count = 1; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`one email<!--ICU ${HEADER_OFFSET + 0}:0-->`); fixture.componentInstance.count = 10; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `a few emails<!--ICU ${HEADER_OFFSET + 0}:0-->`, ); fixture.componentInstance.count = 20; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `lots of emails<!--ICU ${HEADER_OFFSET + 0}:0-->`, ); fixture.componentInstance.count = 0; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`no email<!--ICU ${HEADER_OFFSET + 0}:0-->`); }); it(`should return the correct plural form for ICU expressions when using "es" locale`, () => { // The "es" locale has a simple plural function that can only handle a few options // (and not string inputs) // // function plural(n: number): number { // if (n === 1) return 1; // return 5; // } // // Compare this to the "ro" locale in the previous test const icuMessage = '{VAR_PLURAL, plural, =0 {no email} =one ' + '{one email} =few {a few emails} =other {lots of emails}}'; loadTranslations({[computeMsgId(icuMessage)]: icuMessage}); registerLocaleData(localeEs); TestBed.configureTestingModule({providers: [{provide: LOCALE_ID, useValue: 'es'}]}); // We could also use `TestBed.overrideProvider(LOCALE_ID, {useValue: 'es'});` const fixture = initWithTemplate( AppComp, ` {count, plural, =0 {no email} =one {one email} =few {a few emails} =other {lots of emails} }`, ); expect(fixture.nativeElement.innerHTML).toEqual(`no email<!--ICU ${HEADER_OFFSET + 0}:0-->`); // Change detection cycle, no model changes fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`no email<!--ICU ${HEADER_OFFSET + 0}:0-->`); fixture.componentInstance.count = 3; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `lots of emails<!--ICU ${HEADER_OFFSET + 0}:0-->`, ); fixture.componentInstance.count = 1; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`one email<!--ICU ${HEADER_OFFSET + 0}:0-->`); fixture.componentInstance.count = 10; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `lots of emails<!--ICU ${HEADER_OFFSET + 0}:0-->`, ); fixture.componentInstance.count = 20; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `lots of emails<!--ICU ${HEADER_OFFSET + 0}:0-->`, ); fixture.componentInstance.count = 0; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`no email<!--ICU ${HEADER_OFFSET + 0}:0-->`); }); it('projection', () => { loadTranslations({ [computeMsgId('{VAR_PLURAL, plural, =1 {one} other {at least {INTERPOLATION} .}}')]: '{VAR_PLURAL, plural, =1 {one} other {at least {INTERPOLATION} .}}', }); @Component({ selector: 'child', template: '<div><ng-content></ng-content></div>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: ` <child i18n>{ value // i18n(ph = "blah"), plural, =1 {one} other {at least {{value}} .} }</child>`, standalone: false, }) class Parent { value = 3; } TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toContain('at least'); }); it('with empty values', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {} 20 {twenty} other {other}}')]: '{VAR_SELECT, select, 10 {} 20 {twenty} other {other}}', }); const fixture = initWithTemplate(AppComp, `{count, select, 10 {} 20 {twenty} other {other}}`); const element = fixture.nativeElement; expect(element).toHaveText('other'); }); it('inside a container when
{ "end_byte": 52160, "start_byte": 45862, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_52166_59863
ng a view via vcr.createEmbeddedView', () => { loadTranslations({ [computeMsgId('{VAR_PLURAL, plural, =1 {ONE} other {OTHER}}')]: '{VAR_PLURAL, plural, =1 {ONE} other {OTHER}}', }); @Directive({ selector: '[someDir]', standalone: false, }) class Dir { constructor( private readonly viewContainerRef: ViewContainerRef, private readonly templateRef: TemplateRef<any>, ) {} ngOnInit() { this.viewContainerRef.createEmbeddedView(this.templateRef); } } @Component({ selector: 'my-cmp', template: ` <div *someDir> <ng-content></ng-content> </div> `, standalone: false, }) class Cmp {} @Component({ selector: 'my-app', template: ` <my-cmp i18n="test" *ngIf="condition">{ count, plural, =1 {ONE} other {OTHER} }</my-cmp> `, standalone: false, }) class App { count = 1; condition = true; } TestBed.configureTestingModule({ declarations: [App, Cmp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain( `<my-cmp><div>ONE<!--ICU ${HEADER_OFFSET + 1}:0--></div><!--container--></my-cmp>`, ); fixture.componentRef.instance.count = 2; fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain( `<my-cmp><div>OTHER<!--ICU ${HEADER_OFFSET + 1}:0--></div><!--container--></my-cmp>`, ); // destroy component fixture.componentInstance.condition = false; fixture.detectChanges(); expect(fixture.debugElement.nativeElement.textContent).toBe(''); // render it again and also change ICU case fixture.componentInstance.condition = true; fixture.componentInstance.count = 1; fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain( `<my-cmp><div>ONE<!--ICU ${HEADER_OFFSET + 1}:0--></div><!--container--></my-cmp>`, ); }); it('with nested ICU expression and inside a container when creating a view via vcr.createEmbeddedView', () => { loadTranslations({ [computeMsgId( '{VAR_PLURAL, plural, =1 {ONE} other {{INTERPOLATION} ' + '{VAR_SELECT, select, cat {cats} dog {dogs} other {animals}}!}}', )]: '{VAR_PLURAL, plural, =1 {ONE} other {{INTERPOLATION} ' + '{VAR_SELECT, select, cat {cats} dog {dogs} other {animals}}!}}', }); let dir: Dir | null = null; @Directive({ selector: '[someDir]', standalone: false, }) class Dir { constructor( private readonly viewContainerRef: ViewContainerRef, private readonly templateRef: TemplateRef<any>, ) { dir = this; } attachEmbeddedView() { this.viewContainerRef.createEmbeddedView(this.templateRef); } } @Component({ selector: 'my-cmp', template: ` <div *someDir> <ng-content></ng-content> </div> `, standalone: false, }) class Cmp {} @Component({ selector: 'my-app', template: ` <my-cmp i18n="test">{ count, plural, =1 {ONE} other {{{count}} {name, select, cat {cats} dog {dogs} other {animals} }!} }</my-cmp> `, standalone: false, }) class App { count = 1; } TestBed.configureTestingModule({ declarations: [App, Cmp, Dir], }); const fixture = TestBed.createComponent(App); fixture.componentRef.instance.count = 2; fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toBe( '<my-cmp><!--container--></my-cmp>', ); dir!.attachEmbeddedView(); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toBe( `<my-cmp><div>2 animals<!--nested ICU 0-->!<!--ICU ${ HEADER_OFFSET + 1 }:1--></div><!--container--></my-cmp>`, ); fixture.componentRef.instance.count = 1; fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toBe( `<my-cmp><div>ONE<!--ICU ${HEADER_OFFSET + 1}:1--></div><!--container--></my-cmp>`, ); }); it('with nested containers', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, A {A } B {B } other {C }}')]: '{VAR_SELECT, select, A {A } B {B } other {C }}', [computeMsgId('{VAR_SELECT, select, A1 {A1 } B1 {B1 } other {C1 }}')]: '{VAR_SELECT, select, A1 {A1 } B1 {B1 } other {C1 }}', [computeMsgId(' {$ICU} ')]: ' {$ICU} ', }); @Component({ selector: 'comp', template: ` <ng-container [ngSwitch]="visible"> <ng-container *ngSwitchCase="isVisible()" i18n> {type, select, A { A } B { B } other { C }} </ng-container> <ng-container *ngSwitchCase="!isVisible()" i18n> {type, select, A1 { A1 } B1 { B1 } other { C1 }} </ng-container> </ng-container> `, standalone: false, }) class Comp { type = 'A'; visible = true; isVisible() { return true; } } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain('A'); fixture.componentInstance.visible = false; fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).not.toContain('A'); expect(fixture.debugElement.nativeElement.innerHTML).toContain('C1'); }); it('with named interpolations', () => { loadTranslations({ [computeMsgId( '{VAR_SELECT, select, A {A - {PH_A}} ' + 'B {B - {PH_B}} other {other - {PH_WITH_SPACES}}}', )]: '{VAR_SELECT, select, A {A (translated) - {PH_A}} ' + 'B {B (translated) - {PH_B}} other {other (translated) - {PH_WITH_SPACES}}}', }); @Component({ selector: 'comp', template: ` <ng-container i18n>{ type, select, A {A - {{ typeA // i18n(ph="PH_A") }}} B {B - {{ typeB // i18n(ph="PH_B") }}} other {other - {{ typeC // i18n(ph="PH WITH SPACES") }}} }</ng-container> `, standalone: false, }) class Comp { type = 'A'; typeA = 'Type A'; typeB = 'Type B'; typeC = 'Type C'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain('A (translated) - Type A'); fixture.componentInstance.type = 'C'; // trigger "other" case fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).not.toContain('A (translated) - Type A'); expect(fixture.debugElement.nativeElement.innerHTML).toContain('other (translated) - Type C'); }); it('should work inside an ng
{ "end_byte": 59863, "start_byte": 52166, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_59869_68736
teOutlet inside an ngFor', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, A {A } B {B } other {other - {PH_WITH_SPACES}}}')]: '{VAR_SELECT, select, A {A } B {B } other {other - {PH_WITH_SPACES}}}', [computeMsgId('{$ICU} ')]: '{$ICU} ', }); @Component({ selector: 'app', template: ` <ng-template #myTemp i18n let-type>{ type, select, A {A } B {B } other {other - {{ typeC // i18n(ph="PH WITH SPACES") }}} } </ng-template> <div *ngFor="let type of types"> <ng-container *ngTemplateOutlet="myTemp; context: {$implicit: type}"> </ng-container> </div> `, standalone: false, }) class AppComponent { types = ['A', 'B', 'C']; } TestBed.configureTestingModule({declarations: [AppComponent]}); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain('A'); expect(fixture.debugElement.nativeElement.innerHTML).toContain('B'); }); it('should use metadata from container element if a message is a single ICU', () => { loadTranslations({idA: "{VAR_SELECT, select, 1 {un} other {plus d'un}}"}); @Component({ selector: 'app', template: ` <div i18n="@@idA">{count, select, 1 {one} other {more than one}}</div> `, standalone: false, }) class AppComponent { count = 2; } TestBed.configureTestingModule({declarations: [AppComponent]}); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain("plus d'un"); }); it('should support ICUs without "other" cases', () => { loadTranslations({ idA: '{VAR_SELECT, select, 1 {un (select)} 2 {deux (select)}}', idB: '{VAR_PLURAL, plural, =1 {un (plural)} =2 {deux (plural)}}', }); @Component({ selector: 'app', template: ` <div i18n="@@idA">{count, select, 1 {one (select)} 2 {two (select)}}</div> - <div i18n="@@idB">{count, plural, =1 {one (plural)} =2 {two (plural)}}</div> `, standalone: false, }) class AppComponent { count = 1; } TestBed.configureTestingModule({declarations: [AppComponent]}); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('un (select) - un (plural)'); fixture.componentInstance.count = 3; fixture.detectChanges(); // there is no ICU case for count=3 expect(fixture.nativeElement.textContent.trim()).toBe('-'); fixture.componentInstance.count = 4; fixture.detectChanges(); // there is no ICU case for count=4, making sure content is still empty expect(fixture.nativeElement.textContent.trim()).toBe('-'); fixture.componentInstance.count = 2; fixture.detectChanges(); // check switching to an existing case after processing an ICU without matching case expect(fixture.nativeElement.textContent.trim()).toBe('deux (select) - deux (plural)'); fixture.componentInstance.count = 1; fixture.detectChanges(); // check that we can go back to the first ICU case expect(fixture.nativeElement.textContent).toBe('un (select) - un (plural)'); }); it('should support nested ICUs without "other" cases', () => { loadTranslations({ idA: '{VAR_SELECT_1, select, A {{VAR_SELECT, select, ' + '1 {un (select)} 2 {deux (select)}}} other {}}', idB: '{VAR_SELECT, select, A {{VAR_PLURAL, plural, ' + '=1 {un (plural)} =2 {deux (plural)}}} other {}}', }); @Component({ selector: 'app', template: ` <div i18n="@@idA">{ type, select, A {{count, select, 1 {one (select)} 2 {two (select)}}} other {} }</div> - <div i18n="@@idB">{ type, select, A {{count, plural, =1 {one (plural)} =2 {two (plural)}}} other {} }</div> `, standalone: false, }) class AppComponent { type = 'A'; count = 1; } TestBed.configureTestingModule({declarations: [AppComponent]}); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('un (select) - un (plural)'); fixture.componentInstance.count = 3; fixture.detectChanges(); // there is no case for count=3 in nested ICU expect(fixture.nativeElement.textContent.trim()).toBe('-'); fixture.componentInstance.count = 4; fixture.detectChanges(); // there is no case for count=4 in nested ICU, making sure content is still empty expect(fixture.nativeElement.textContent.trim()).toBe('-'); fixture.componentInstance.count = 2; fixture.detectChanges(); // check switching to an existing case after processing nested ICU without matching // case expect(fixture.nativeElement.textContent.trim()).toBe('deux (select) - deux (plural)'); fixture.componentInstance.count = 1; fixture.detectChanges(); // check that we can go back to the first case in nested ICU expect(fixture.nativeElement.textContent).toBe('un (select) - un (plural)'); fixture.componentInstance.type = 'B'; fixture.detectChanges(); // check that nested ICU is removed if root ICU case has changed expect(fixture.nativeElement.textContent.trim()).toBe('-'); }); it('should support ICUs with pipes', () => { loadTranslations({ idA: '{VAR_SELECT, select, 1 {{INTERPOLATION} article} 2 {deux articles}}', }); @Component({ selector: 'app', template: ` <div i18n="@@idA">{count$ | async, select, 1 {{{count$ | async}} item} 2 {two items}}</div> `, standalone: false, }) class AppComponent { count$ = new BehaviorSubject<number>(1); } TestBed.configureTestingModule({ imports: [CommonModule], declarations: [AppComponent], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1 article'); fixture.componentInstance.count$.next(3); fixture.detectChanges(); // there is no ICU case for count=3, expecting empty content expect(fixture.nativeElement.textContent.trim()).toBe(''); fixture.componentInstance.count$.next(2); fixture.detectChanges(); // checking the second ICU case expect(fixture.nativeElement.textContent.trim()).toBe('deux articles'); }); it('should handle select expressions without an `other` parameter inside a template', () => { const fixture = initWithTemplate( AppComp, ` <ng-container *ngFor="let item of items">{item.value, select, 0 {A} 1 {B} 2 {C}}</ng-container> `, ); fixture.componentInstance.items = [{value: 0}, {value: 1}, {value: 1337}]; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('AB'); fixture.componentInstance.items[0].value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('CB'); }); it('should render an element whose case did not match initially', () => { const fixture = initWithTemplate( AppComp, ` <p *ngFor="let item of items">{item.value, select, 0 {A} 1 {B} 2 {C}}</p> `, ); fixture.componentInstance.items = [{value: 0}, {value: 1}, {value: 1337}]; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('AB'); fixture.componentInstance.items[2].value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('ABC'); }); it('should remove an element whose case matched initially, but does not anymore', () => { const fixture = initWithTemplate( AppComp, ` <p *ngFor="let item of items">{item.value, select, 0 {A} 1 {B} 2 {C}}</p> `, ); fixture.componentInstance.items = [{value: 0}, {value: 1}]; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('AB'); fixture.componentInstance.items[0].value = 1337; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('B'); }); }); describe('should support attri
{ "end_byte": 68736, "start_byte": 59869, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_68740_68777
s', () => { it('text', () => {
{ "end_byte": 68777, "start_byte": 68740, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_68778_77459
loadTranslations({[computeMsgId('text')]: 'texte'}); const fixture = initWithTemplate(AppComp, `<div i18n i18n-title title='text'></div>`); expect(fixture.nativeElement.innerHTML).toEqual(`<div title="texte"></div>`); }); it('interpolations', () => { loadTranslations({[computeMsgId('hello {$INTERPOLATION}')]: 'bonjour {$INTERPOLATION}'}); const fixture = initWithTemplate( AppComp, `<div i18n i18n-title title="hello {{name}}"></div>`, ); expect(fixture.nativeElement.innerHTML).toEqual(`<div title="bonjour Angular"></div>`); fixture.componentRef.instance.name = 'John'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`<div title="bonjour John"></div>`); }); it('with pipes', () => { loadTranslations({[computeMsgId('hello {$INTERPOLATION}')]: 'bonjour {$INTERPOLATION}'}); const fixture = initWithTemplate( AppComp, `<div i18n i18n-title title="hello {{name | uppercase}}"></div>`, ); expect(fixture.nativeElement.innerHTML).toEqual(`<div title="bonjour ANGULAR"></div>`); }); it('multiple attributes', () => { loadTranslations({ [computeMsgId('hello {$INTERPOLATION} - {$INTERPOLATION_1}')]: 'bonjour {$INTERPOLATION} - {$INTERPOLATION_1}', [computeMsgId('bye {$INTERPOLATION} - {$INTERPOLATION_1}')]: 'au revoir {$INTERPOLATION} - {$INTERPOLATION_1}', }); const fixture = initWithTemplate( AppComp, `<input i18n i18n-title title="hello {{name}} - {{count}}" i18n-placeholder placeholder="bye {{count}} - {{name}}">`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<input title="bonjour Angular - 0" placeholder="au revoir 0 - Angular">`, ); fixture.componentRef.instance.name = 'John'; fixture.componentRef.instance.count = 5; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<input title="bonjour John - 5" placeholder="au revoir 5 - John">`, ); }); it('on removed elements', () => { loadTranslations({ [computeMsgId('text')]: 'texte', [computeMsgId('{$START_TAG_SPAN}content{$CLOSE_TAG_SPAN}')]: 'contenu', }); const fixture = initWithTemplate( AppComp, `<div i18n><span i18n-title title="text">content</span></div>`, ); expect(fixture.nativeElement.innerHTML).toEqual(`<div>contenu</div>`); }); it('with custom interpolation config', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}', 'm')]: 'Bonjour {$INTERPOLATION}'}); const interpolation = ['{%', '%}'] as [string, string]; TestBed.overrideComponent(AppComp, {set: {interpolation}}); const fixture = initWithTemplate( AppComp, `<div i18n-title="m|d" title="Hello {% name %}"></div>`, ); const element = fixture.nativeElement.firstChild; expect(element.title).toBe('Bonjour Angular'); }); it('in nested template', () => { loadTranslations({[computeMsgId('Item {$INTERPOLATION}', 'm')]: 'Article {$INTERPOLATION}'}); const fixture = initWithTemplate( AppComp, ` <div *ngFor='let item of [1,2,3]'> <div i18n-title='m|d' title='Item {{ item }}'></div> </div>`, ); const element = fixture.nativeElement; for (let i = 0; i < element.children.length; i++) { const child = element.children[i]; expect((child as any).innerHTML).toBe(`<div title="Article ${i + 1}"></div>`); } }); it('should add i18n attributes on self-closing tags', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); const fixture = initWithTemplate( AppComp, `<img src="logo.png" i18n-title title="Hello {{ name }}">`, ); const element = fixture.nativeElement.firstChild; expect(element.title).toBe('Bonjour Angular'); }); it('should process i18n attributes on explicit <ng-template> elements', () => { const titleDirInstances: TitleDir[] = []; loadTranslations({[computeMsgId('Hello')]: 'Bonjour'}); @Directive({ selector: '[title]', standalone: false, }) class TitleDir { @Input() title = ''; constructor() { titleDirInstances.push(this); } } @Component({ selector: 'comp', template: '<ng-template i18n-title title="Hello"></ng-template>', standalone: false, }) class Comp {} TestBed.configureTestingModule({ declarations: [Comp, TitleDir], }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); // make sure we only match `TitleDir` once expect(titleDirInstances.length).toBe(1); expect(titleDirInstances[0].title).toBe('Bonjour'); }); it('should match directive only once in case i18n attrs are present on inline template', () => { const titleDirInstances: TitleDir[] = []; loadTranslations({[computeMsgId('Hello')]: 'Bonjour'}); @Directive({ selector: '[title]', standalone: false, }) class TitleDir { @Input() title: string = ''; constructor(public elRef: ElementRef) { titleDirInstances.push(this); } } @Component({ selector: 'my-cmp', template: ` <button *ngIf="true" i18n-title title="Hello"></button> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({ imports: [CommonModule], declarations: [Cmp, TitleDir], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); // make sure we only match `TitleDir` once and on the right element expect(titleDirInstances.length).toBe(1); expect(titleDirInstances[0].elRef.nativeElement instanceof HTMLButtonElement).toBeTruthy(); expect(titleDirInstances[0].title).toBe('Bonjour'); }); it('should support static i18n attributes on inline templates', () => { loadTranslations({[computeMsgId('Hello')]: 'Bonjour'}); @Component({ selector: 'my-cmp', template: ` <div *ngIf="true" i18n-title title="Hello"></div> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({ imports: [CommonModule], declarations: [Cmp], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(fixture.nativeElement.firstChild.title).toBe('Bonjour'); }); it('should allow directive inputs (as an interpolated prop) on <ng-template>', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); let dirInstance: WithInput; @Directive({ selector: '[dir]', standalone: false, }) class WithInput { constructor() { dirInstance = this; } @Input() dir: string = ''; } @Component({ selector: 'my-app', template: '<ng-template i18n-dir dir="Hello {{ name }}"></ng-template>', standalone: false, }) class TestComp { name = 'Angular'; } TestBed.configureTestingModule({declarations: [TestComp, WithInput]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(dirInstance!.dir).toBe('Bonjour Angular'); }); it( 'should allow directive inputs (as interpolated props)' + 'on <ng-template> with structural directives present', () => { loadTranslations({[computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}'}); let dirInstance: WithInput; @Directive({ selector: '[dir]', standalone: false, }) class WithInput { constructor() { dirInstance = this; } @Input() dir: string = ''; } @Component({ selector: 'my-app', template: '<ng-template *ngIf="true" i18n-dir dir="Hello {{ name }}"></ng-template>', standalone: false, }) class TestComp { name = 'Angular'; } TestBed.configureTestingModule({declarations: [TestComp, WithInput]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(dirInstance!.dir).toBe('Bonjour Angular'); }, ); it('should apply i18n attrib
{ "end_byte": 77459, "start_byte": 68778, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_77465_85442
uring second template pass', () => { loadTranslations({[computeMsgId('Set')]: 'Set'}); @Directive({ selector: '[test]', inputs: ['test'], exportAs: 'dir', standalone: false, }) class Dir {} @Component({ selector: 'other', template: `<div i18n #ref="dir" test="Set" i18n-test="This is also a test"></div>`, standalone: false, }) class Other {} @Component({ selector: 'blah', template: ` <other></other> <other></other> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({ declarations: [Dir, Cmp, Other], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(fixture.debugElement.children[0].children[0].references['ref'].test).toBe('Set'); expect(fixture.debugElement.children[1].children[0].references['ref'].test).toBe('Set'); }); it('with complex expressions', () => { loadTranslations({ [computeMsgId('{$INTERPOLATION} - {$INTERPOLATION_1} - {$INTERPOLATION_2}')]: '{$INTERPOLATION} - {$INTERPOLATION_1} - {$INTERPOLATION_2} (fr)', }); const fixture = initWithTemplate( AppComp, ` <div i18n-title title="{{ name | uppercase }} - {{ obj?.a?.b }} - {{ obj?.getA()?.b }}"></div> `, ); // the `obj` field is not yet defined, so 2nd and 3rd interpolations return empty // strings expect(fixture.nativeElement.firstChild.title).toEqual(`ANGULAR - - (fr)`); fixture.componentRef.instance.obj = { a: {b: 'value 1'}, getA: () => ({b: 'value 2'}), }; fixture.detectChanges(); expect(fixture.nativeElement.firstChild.title).toEqual(`ANGULAR - value 1 - value 2 (fr)`); }); it('should support i18n attributes on <ng-container> elements', () => { loadTranslations({[computeMsgId('Hello', 'meaning')]: 'Bonjour'}); @Directive({ selector: '[mydir]', standalone: false, }) class Dir { @Input() mydir: string = ''; } @Component({ selector: 'my-cmp', template: ` <ng-container i18n-mydir="meaning|description" mydir="Hello"></ng-container> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({ declarations: [Cmp, Dir], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const dir = fixture.debugElement.childNodes[0].injector.get(Dir); expect(dir.mydir).toEqual('Bonjour'); }); }); describe('empty translations', () => { it('should replace existing text content with empty translation', () => { loadTranslations({[computeMsgId('Some Text')]: ''}); const fixture = initWithTemplate(AppComp, '<div i18n>Some Text</div>'); expect(fixture.nativeElement.textContent).toBe(''); }); it('should replace existing DOM elements with empty translation', () => { loadTranslations({ [computeMsgId( ' Start {$START_TAG_DIV}DIV{$CLOSE_TAG_DIV}' + '{$START_TAG_SPAN}SPAN{$CLOSE_TAG_SPAN} End ', )]: '', }); const fixture = initWithTemplate( AppComp, ` <div i18n> Start <div>DIV</div> <span>SPAN</span> End </div> `, ); expect(fixture.nativeElement.textContent).toBe(''); }); it('should replace existing ICU content with empty translation', () => { loadTranslations({ [computeMsgId('{VAR_PLURAL, plural, =0 {zero} other {more than zero}}')]: '', }); const fixture = initWithTemplate( AppComp, ` <div i18n>{count, plural, =0 {zero} other {more than zero}}</div> `, ); expect(fixture.nativeElement.textContent).toBe(''); }); }); it('should work with directives and host bindings', () => { let directiveInstances: ClsDir[] = []; @Directive({ selector: '[test]', standalone: false, }) class ClsDir { @HostBinding('className') klass = 'foo'; constructor() { directiveInstances.push(this); } } @Component({ selector: `my-app`, template: ` <div i18n test i18n-title title="start {{exp1}} middle {{exp2}} end" outer> trad: {exp1, plural, =0 {no <b title="none">emails</b>!} =1 {one <i>email</i>} other {{{exp1}} emails} } </div><div test inner></div>`, standalone: false, }) class MyApp { exp1 = 1; exp2 = 2; } TestBed.configureTestingModule({declarations: [ClsDir, MyApp]}); loadTranslations({ // Note that this translation switches the order of the expressions! [computeMsgId('start {$INTERPOLATION} middle {$INTERPOLATION_1} end')]: 'début {$INTERPOLATION_1} milieu {$INTERPOLATION} fin', [computeMsgId( '{VAR_PLURAL, plural, =0 {no {START_BOLD_TEXT}emails{CLOSE_BOLD_TEXT}!} =1 {one {START_ITALIC_TEXT}email{CLOSE_ITALIC_TEXT}} other {{INTERPOLATION} emails}}', )]: '{VAR_PLURAL, plural, =0 {aucun {START_BOLD_TEXT}email{CLOSE_BOLD_TEXT}!} =1 {un {START_ITALIC_TEXT}email{CLOSE_ITALIC_TEXT}} other {{INTERPOLATION} emails}}', [computeMsgId(' trad: {$ICU} ')]: ' traduction: {$ICU} ', }); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const outerDiv: HTMLElement = fixture.nativeElement.querySelector('div[outer]'); const innerDiv: HTMLElement = fixture.nativeElement.querySelector('div[inner]'); // Note that ideally we'd just compare the innerHTML here, but different browsers return // the order of attributes differently. E.g. most browsers preserve the declaration // order, but IE does not. expect(outerDiv.getAttribute('title')).toBe('début 2 milieu 1 fin'); expect(outerDiv.getAttribute('class')).toBe('foo'); expect(outerDiv.textContent!.trim()).toBe('traduction: un email'); expect(innerDiv.getAttribute('class')).toBe('foo'); directiveInstances.forEach((instance) => (instance.klass = 'bar')); fixture.componentRef.instance.exp1 = 2; fixture.componentRef.instance.exp2 = 3; fixture.detectChanges(); expect(outerDiv.getAttribute('title')).toBe('début 3 milieu 2 fin'); expect(outerDiv.getAttribute('class')).toBe('bar'); expect(outerDiv.textContent!.trim()).toBe('traduction: 2 emails'); expect(innerDiv.getAttribute('class')).toBe('bar'); }); it('should handle i18n attribute with directive inputs', () => { let calledTitle = false; let calledValue = false; @Component({ selector: 'my-comp', template: '', standalone: false, }) class MyComp { t!: string; @Input() get title() { return this.t; } set title(title) { calledTitle = true; this.t = title; } @Input() get value() { return this.val; } set value(value: string) { calledValue = true; this.val = value; } val!: string; } TestBed.configureTestingModule({declarations: [AppComp, MyComp]}); loadTranslations({ [computeMsgId('Hello {$INTERPOLATION}')]: 'Bonjour {$INTERPOLATION}', [computeMsgId('works')]: 'fonctionne', }); const fixture = initWithTemplate( AppComp, `<my-comp i18n i18n-title title="works" i18n-value="hi" value="Hello {{name}}"></my-comp>`, ); fixture.detectChanges(); const directive = fixture.debugElement.children[0].injector.get(MyComp); expect(calledValue).toEqual(true); expect(calledTitle).toEqual(true); expect(directive.value).toEqual(`Bonjour Angular`); expect(directive.title).toEqual(`fonctionne`); }); it('should support adding/moving/
{ "end_byte": 85442, "start_byte": 77465, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_85446_86631
ving nodes', () => { loadTranslations({ [computeMsgId( '{$START_TAG_DIV2}{$CLOSE_TAG_DIV2}' + '{$START_TAG_DIV3}{$CLOSE_TAG_DIV3}' + '{$START_TAG_DIV4}{$CLOSE_TAG_DIV4}' + '{$START_TAG_DIV5}{$CLOSE_TAG_DIV5}' + '{$START_TAG_DIV6}{$CLOSE_TAG_DIV6}' + '{$START_TAG_DIV7}{$CLOSE_TAG_DIV7}' + '{$START_TAG_DIV8}{$CLOSE_TAG_DIV8}', )]: '{$START_TAG_DIV2}{$CLOSE_TAG_DIV2}' + '{$START_TAG_DIV8}{$CLOSE_TAG_DIV8}' + '{$START_TAG_DIV4}{$CLOSE_TAG_DIV4}' + '{$START_TAG_DIV5}{$CLOSE_TAG_DIV5}Bonjour monde' + '{$START_TAG_DIV3}{$CLOSE_TAG_DIV3}' + '{$START_TAG_DIV7}{$CLOSE_TAG_DIV7}', }); const fixture = initWithTemplate( AppComp, ` <div i18n> <div2></div2> <div3></div3> <div4></div4> <div5></div5> <div6></div6> <div7></div7> <div8></div8> </div>`, ); expect(fixture.nativeElement.innerHTML).toEqual( `<div><div2></div2><div8></div8><div4></div4><div5></div5>Bonjour monde<div3></div3><div7></div7></div>`, ); }); describe('projection', () => {
{ "end_byte": 86631, "start_byte": 85446, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_86635_95508
('should project the translations', () => { @Component({ selector: 'child', template: '<p><ng-content></ng-content></p>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: ` <div i18n> <child>I am projected from <b i18n-title title="Child of {{name}}">{{name}}<remove-me-1></remove-me-1></b> <remove-me-2></remove-me-2> </child> <remove-me-3></remove-me-3> </div>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child]}); loadTranslations({ [computeMsgId('Child of {$INTERPOLATION}')]: 'Enfant de {$INTERPOLATION}', [computeMsgId( '{$START_TAG_CHILD}I am projected from' + ' {$START_BOLD_TEXT}{$INTERPOLATION}{$START_TAG_REMOVE_ME_1}{$CLOSE_TAG_REMOVE_ME_1}{$CLOSE_BOLD_TEXT}' + '{$START_TAG_REMOVE_ME_2}{$CLOSE_TAG_REMOVE_ME_2}' + '{$CLOSE_TAG_CHILD}' + '{$START_TAG_REMOVE_ME_3}{$CLOSE_TAG_REMOVE_ME_3}', )]: '{$START_TAG_CHILD}Je suis projeté depuis {$START_BOLD_TEXT}{$INTERPOLATION}{$CLOSE_BOLD_TEXT}{$CLOSE_TAG_CHILD}', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div><child><p>Je suis projeté depuis <b title="Enfant de Parent">Parent</b></p></child></div>`, ); }); it('should project a translated i18n block', () => { @Component({ selector: 'child', template: '<p><ng-content></ng-content></p>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: ` <div> <child> <any></any> <b i18n i18n-title title="Child of {{name}}">I am projected from {{name}}</b> <any></any> </child> </div>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child]}); loadTranslations({ [computeMsgId('Child of {$INTERPOLATION}')]: 'Enfant de {$INTERPOLATION}', [computeMsgId('I am projected from {$INTERPOLATION}')]: 'Je suis projeté depuis {$INTERPOLATION}', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<div><child><p><any></any><b title="Enfant de Parent">Je suis projeté depuis Parent</b><any></any></p></child></div>`, ); // it should be able to render a new component with the same template code const fixture2 = TestBed.createComponent(Parent); fixture2.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(fixture2.nativeElement.innerHTML); fixture2.componentRef.instance.name = 'Parent 2'; fixture2.detectChanges(); expect(fixture2.nativeElement.innerHTML).toEqual( `<div><child><p><any></any><b title="Enfant de Parent 2">Je suis projeté depuis Parent 2</b><any></any></p></child></div>`, ); // The first fixture should not have changed expect(fixture.nativeElement.innerHTML).not.toEqual(fixture2.nativeElement.innerHTML); }); it('should re-project translations when multiple projections', () => { @Component({ selector: 'grand-child', template: '<div><ng-content></ng-content></div>', standalone: false, }) class GrandChild {} @Component({ selector: 'child', template: '<grand-child><ng-content></ng-content></grand-child>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child i18n><b>Hello</b> World!</child>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child, GrandChild]}); loadTranslations({ [computeMsgId('{$START_BOLD_TEXT}Hello{$CLOSE_BOLD_TEXT} World!')]: '{$START_BOLD_TEXT}Bonjour{$CLOSE_BOLD_TEXT} monde!', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<child><grand-child><div><b>Bonjour</b> monde!</div></grand-child></child>', ); }); it('should be able to remove projected placeholders', () => { @Component({ selector: 'grand-child', template: '<div><ng-content></ng-content></div>', standalone: false, }) class GrandChild {} @Component({ selector: 'child', template: '<grand-child><ng-content></ng-content></grand-child>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child i18n><b>Hello</b> World!</child>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child, GrandChild]}); loadTranslations({ [computeMsgId('{$START_BOLD_TEXT}Hello{$CLOSE_BOLD_TEXT} World!')]: 'Bonjour monde!', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<child><grand-child><div>Bonjour monde!</div></grand-child></child>', ); }); it('should project translations with selectors', () => { @Component({ selector: 'child', template: `<ng-content select='span'></ng-content>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: ` <child i18n> <span title="keepMe"></span> <span title="deleteMe"></span> </child> `, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); loadTranslations({ [computeMsgId('{$START_TAG_SPAN}{$CLOSE_TAG_SPAN}{$START_TAG_SPAN_1}{$CLOSE_TAG_SPAN}')]: '{$START_TAG_SPAN}Contenu{$CLOSE_TAG_SPAN}', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<child><span title="keepMe">Contenu</span></child>', ); }); it('should project content in i18n blocks', () => { @Component({ selector: 'child', template: `<div i18n>Content projected from <ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child>{{name}}</child>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child]}); loadTranslations({ [computeMsgId('Content projected from {$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT}')]: 'Contenu projeté depuis {$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT}', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<child><div>Contenu projeté depuis Parent</div></child>`, ); fixture.componentRef.instance.name = 'Parent component'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<child><div>Contenu projeté depuis Parent component</div></child>`, ); }); it('should project content in i18n blocks with placeholders', () => { @Component({ selector: 'child', template: `<div i18n>Content projected from <ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><b>{{name}}</b></child>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child]}); loadTranslations({ [computeMsgId('Content projected from {$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT}')]: '{$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT} a projeté le contenu', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<child><div><b>Parent</b> a projeté le contenu</div></child>`, ); }); it('should project translated content in
{ "end_byte": 95508, "start_byte": 86635, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_95514_104108
locks', () => { @Component({ selector: 'child', template: `<div i18n>Child content <ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child i18n>and projection from {{name}}</child>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child]}); loadTranslations({ [computeMsgId('Child content {$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT}')]: 'Contenu enfant {$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT}', [computeMsgId('and projection from {$INTERPOLATION}')]: 'et projection depuis {$INTERPOLATION}', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<child><div>Contenu enfant et projection depuis Parent</div></child>`, ); }); it('should project bare ICU expressions', () => { loadTranslations({ [computeMsgId('{VAR_PLURAL, plural, =1 {one} other {at least {INTERPOLATION} .}}')]: '{VAR_PLURAL, plural, =1 {one} other {at least {INTERPOLATION} .}}', }); @Component({ selector: 'child', template: '<div><ng-content></ng-content></div>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: ` <child i18n>{ value // i18n(ph = "blah"), plural, =1 {one} other {at least {{value}} .} }</child>`, standalone: false, }) class Parent { value = 3; } TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toContain('at least'); }); it('should project ICUs in i18n blocks', () => { @Component({ selector: 'child', template: `<div i18n>Child content <ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child i18n>and projection from {name, select, angular {Angular} other {{{name}}}}</child>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child]}); loadTranslations({ [computeMsgId('{VAR_SELECT, select, angular {Angular} other {{INTERPOLATION}}}')]: '{VAR_SELECT, select, angular {Angular} other {{INTERPOLATION}}}', [computeMsgId('Child content {$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT}')]: 'Contenu enfant {$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT}', [computeMsgId('and projection from {$ICU}')]: 'et projection depuis {$ICU}', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<child><div>Contenu enfant et projection depuis Parent<!--ICU ${ HEADER_OFFSET + 1 }:0--></div></child>`, ); fixture.componentRef.instance.name = 'angular'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( `<child><div>Contenu enfant et projection depuis Angular<!--ICU ${ HEADER_OFFSET + 1 }:0--></div></child>`, ); }); it(`shouldn't project deleted projections in i18n blocks`, () => { @Component({ selector: 'child', template: `<div i18n>Child content <ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child i18n>and projection from {{name}}</child>`, standalone: false, }) class Parent { name: string = 'Parent'; } TestBed.configureTestingModule({declarations: [Parent, Child]}); loadTranslations({ [computeMsgId('Child content {$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT}')]: 'Contenu enfant', [computeMsgId('and projection from {$INTERPOLATION}')]: 'et projection depuis {$INTERPOLATION}', }); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(`<child><div>Contenu enfant</div></child>`); }); it('should display/destroy projected i18n content', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, A {A} B {B} other {other}}')]: '{VAR_SELECT, select, A {A} B {B} other {other}}', }); @Component({ selector: 'app', template: ` <ng-container>(<ng-content></ng-content>)</ng-container> `, standalone: false, }) class MyContentApp {} @Component({ selector: 'my-app', template: ` <app i18n *ngIf="condition">{type, select, A {A} B {B} other {other}}</app> `, standalone: false, }) class MyApp { type = 'A'; condition = true; } TestBed.configureTestingModule({declarations: [MyApp, MyContentApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('(A)'); // change `condition` to remove <app> fixture.componentInstance.condition = false; fixture.detectChanges(); // should not contain 'A' expect(fixture.nativeElement.textContent).toBe(''); // display <app> again fixture.componentInstance.type = 'B'; fixture.componentInstance.condition = true; fixture.detectChanges(); // expect that 'B' is now displayed expect(fixture.nativeElement.textContent).toContain('(B)'); }); }); describe('queries', () => { function toHtml(element: Element): string { return element.innerHTML .replace(/\sng-reflect-\S*="[^"]*"/g, '') .replace(/<!--bindings=\{(\W.*\W\s*)?\}-->/g, ''); } it('detached nodes should still be part of query', () => { @Directive({ selector: '[text]', inputs: ['text'], exportAs: 'textDir', standalone: false, }) class TextDirective { text: string | undefined; constructor() {} } @Component({ selector: 'div-query', template: '<ng-container #vc></ng-container>', standalone: false, }) class DivQuery { @ContentChild(TemplateRef, {static: true}) template!: TemplateRef<any>; @ViewChild('vc', {read: ViewContainerRef, static: true}) vc!: ViewContainerRef; @ContentChildren(TextDirective, {descendants: true}) query!: QueryList<TextDirective>; create() { this.vc.createEmbeddedView(this.template); } destroy() { this.vc.clear(); } } TestBed.configureTestingModule({declarations: [TextDirective, DivQuery]}); loadTranslations({ [computeMsgId( '{$START_TAG_NG_TEMPLATE}{$START_TAG_DIV_1}' + '{$START_TAG_DIV}' + '{$START_TAG_SPAN}Content{$CLOSE_TAG_SPAN}' + '{$CLOSE_TAG_DIV}' + '{$CLOSE_TAG_DIV}{$CLOSE_TAG_NG_TEMPLATE}', )]: '{$START_TAG_NG_TEMPLATE}Contenu{$CLOSE_TAG_NG_TEMPLATE}', }); const fixture = initWithTemplate( AppComp, ` <div-query #q i18n> <ng-template> <div> <div *ngIf="visible"> <span text="1">Content</span> </div> </div> </ng-template> </div-query> `, ); const q = fixture.debugElement.children[0].references['q']; expect(q.query.length).toEqual(0); // Create embedded view q.create(); fixture.detectChanges(); expect(q.query.length).toEqual(1); expect(toHtml(fixture.nativeElement)).toEqual( `<div-query>Contenu<!--ng-container--></div-query>`, ); // Disable ng-if fixture.componentInstance.visible = false; fixture.detectChanges(); expect(q.query.length).toEqual(0); expect(toHtml(fixture.nativeElement)).toEqual( `<div-query>Contenu<!--ng-container--></div-query>`, ); }); }); describe('invalid translations handling', (
{ "end_byte": 104108, "start_byte": 95514, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_104112_112608
{ it('should throw in case invalid ICU is present in a template', () => { // Error message is produced by Compiler. expect(() => initWithTemplate(AppComp, '{count, select, 10 {ten} other {other}'), ).toThrowError( /Invalid ICU message. Missing '}'. \("{count, select, 10 {ten} other {other}\[ERROR ->\]"\)/, ); }); it('should throw in case invalid ICU is present in translation', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {ten} other {other}}')]: // Missing "}" at the end of translation. '{VAR_SELECT, select, 10 {dix} other {autre}', }); // Error message is produced at runtime. expect(() => initWithTemplate(AppComp, '{count, select, 10 {ten} other {other}}'), ).toThrowError( /Unable to parse ICU expression in "{�0�, select, 10 {dix} other {autre}" message./, ); }); it('should throw in case unescaped curly braces are present in a template', () => { // Error message is produced by Compiler. expect(() => initWithTemplate(AppComp, 'Text { count }')).toThrowError( /Do you have an unescaped "{" in your template\? Use "{{ '{' }}"\) to escape it/, ); }); it('should throw in case curly braces are added into translation', () => { loadTranslations({ // Curly braces which were not present in a template were added into translation. [computeMsgId('Text')]: 'Text { count }', }); expect(() => initWithTemplate(AppComp, '<div i18n>Text</div>')).toThrowError( /Unable to parse ICU expression in "Text { count }" message./, ); }); }); it('should handle extra HTML in translation as plain text', () => { loadTranslations({ // Translation contains HTML tags that were not present in original message. [computeMsgId('Text')]: 'Text <div *ngIf="true">Extra content</div>', }); const fixture = initWithTemplate(AppComp, '<div i18n>Text</div>'); const element = fixture.nativeElement; expect(element).toHaveText('Text <div *ngIf="true">Extra content</div>'); }); it('should reflect lifecycle hook changes in text interpolations in i18n block', () => { @Directive({ selector: 'input', standalone: false, }) class InputsDir { constructor(private elementRef: ElementRef) {} ngOnInit() { this.elementRef.nativeElement.value = 'value set in Directive.ngOnInit'; } } @Component({ template: ` <input #myinput> <div i18n>{{myinput.value}}</div> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, InputsDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('value set in Directive.ngOnInit'); }); it('should reflect lifecycle hook changes in text interpolations in i18n attributes', () => { @Directive({ selector: 'input', standalone: false, }) class InputsDir { constructor(private elementRef: ElementRef) {} ngOnInit() { this.elementRef.nativeElement.value = 'value set in Directive.ngOnInit'; } } @Component({ template: ` <input #myinput> <div i18n-title title="{{myinput.value}}"></div> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, InputsDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('div').title).toContain( 'value set in Directive.ngOnInit', ); }); it('should not alloc expando slots when there is no new variable to create', () => { loadTranslations({ [computeMsgId('{$START_TAG_DIV} Some content {$CLOSE_TAG_DIV}')]: '{$START_TAG_DIV} Some content {$CLOSE_TAG_DIV}', [computeMsgId( '{$START_TAG_SPAN_1}{$ICU}{$CLOSE_TAG_SPAN} - {$START_TAG_SPAN_1}{$ICU_1}{$CLOSE_TAG_SPAN}', )]: '{$START_TAG_SPAN_1}{$ICU}{$CLOSE_TAG_SPAN} - {$START_TAG_SPAN_1}{$ICU_1}{$CLOSE_TAG_SPAN}', }); @Component({ template: ` <div dialog i18n> <div *ngIf="data"> Some content </div> </div> <button [close]="true">Button label</button> `, standalone: false, }) class ContentElementDialog { data = false; } TestBed.configureTestingModule({declarations: [DialogDir, CloseBtn, ContentElementDialog]}); const fixture = TestBed.createComponent(ContentElementDialog); fixture.detectChanges(); // Remove the reflect attribute, because the attribute order in innerHTML // isn't guaranteed in different browsers so it could throw off our assertions. const button = fixture.nativeElement.querySelector('button'); button.removeAttribute('ng-reflect-dialog-result'); expect(fixture.nativeElement.innerHTML).toEqual(`<div dialog=""><!--bindings={ "ng-reflect-ng-if": "false" }--></div><button title="Close dialog">Button label</button>`); }); describe('ngTemplateOutlet', () => { it('should work with i18n content that includes elements', () => { loadTranslations({ [computeMsgId('{$START_TAG_SPAN}A{$CLOSE_TAG_SPAN} B ')]: '{$START_TAG_SPAN}a{$CLOSE_TAG_SPAN} b', }); const fixture = initWithTemplate( AppComp, ` <ng-container *ngTemplateOutlet="tmpl"></ng-container> <ng-template #tmpl i18n> <span>A</span> B </ng-template> `, ); expect(fixture.nativeElement.textContent).toContain('a b'); }); it('should work with i18n content that includes other templates (*ngIf)', () => { loadTranslations({ [computeMsgId('{$START_TAG_SPAN}A{$CLOSE_TAG_SPAN} B ')]: '{$START_TAG_SPAN}a{$CLOSE_TAG_SPAN} b', }); const fixture = initWithTemplate( AppComp, ` <ng-container *ngTemplateOutlet="tmpl"></ng-container> <ng-template #tmpl i18n> <span *ngIf="visible">A</span> B </ng-template> `, ); expect(fixture.nativeElement.textContent).toContain('a b'); }); it('should work with i18n content that includes projection', () => { loadTranslations({ [computeMsgId('{$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT} B ')]: '{$START_TAG_NG_CONTENT}{$CLOSE_TAG_NG_CONTENT} b', }); @Component({ selector: 'projector', template: ` <ng-container *ngTemplateOutlet="tmpl"></ng-container> <ng-template #tmpl i18n> <ng-content></ng-content> B </ng-template> `, standalone: false, }) class Projector {} @Component({ selector: 'app', template: ` <projector>a</projector> `, standalone: false, }) class AppComponent {} TestBed.configureTestingModule({declarations: [AppComponent, Projector]}); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('a b'); }); }); describe('viewContainerRef with i18n', () => { it('should create ViewContainerRef with i18n', () => { // This test demonstrates an issue with creating a `ViewContainerRef` and having i18n at the // parent element. The reason this broke is that in this case the `ViewContainerRef` creates // an dynamic anchor comment but uses `HostTNode` for it which is incorrect. `appendChild` // then tries to add internationalization to the comment node and fails. @Component({ template: ` <div i18n>before|<div myDir>inside</div>|after</div> `, standalone: false, }) class MyApp {} @Directive({ selector: '[myDir]', standalone: false, }) class MyDir { constructor(vcRef: ViewContainerRef) { myDir = this; } } let myDir!: MyDir; TestBed.configureTestingModule({declarations: [MyApp, MyDir]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(myDir).toBeDefined(); expect(fixture.nativeElement.textContent).toEqual(`before|inside|after`); }); }); it('should create ICU with attributes', () => {
{ "end_byte": 112608, "start_byte": 104112, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_112612_120627
// This test demonstrates an issue with setting attributes on ICU elements. // NOTE: This test is extracted from g3. @Component({ template: ` <h1 class="num-cart-items" i18n *ngIf="true">{ registerItemCount, plural, =0 {Your cart} =1 {Your cart <span class="item-count">(1 item)</span>} other { Your cart <span class="item-count">({{ registerItemCount }} items)</span> } }</h1>`, standalone: false, }) class MyApp { registerItemCount = 1; } TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual(`Your cart (1 item)`); }); it('should not insertBeforeIndex non-projected content text', () => { // This test demonstrates an issue with setting attributes on ICU elements. // NOTE: This test is extracted from g3. @Component({ template: `<div i18n>before|<child>TextNotProjected</child>|after</div>`, standalone: false, }) class MyApp {} @Component({ selector: 'child', template: 'CHILD', standalone: false, }) class Child {} TestBed.configureTestingModule({declarations: [MyApp, Child]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual(`before|CHILD|after`); }); it('should create a pipe inside i18n block', () => { // This test demonstrates an issue with i18n messing up `getCurrentTNode` which subsequently // breaks the DI. The issue is that the `i18nStartFirstCreatePass` would create placeholder // NODES, and than leave `getCurrentTNode` in undetermined state which would then break DI. // NOTE: This test is extracted from g3. @Component({ template: ` <div i18n [title]="null | async"><div>A</div></div> <div i18n>{{(null | async)||'B'}}<div></div></div>`, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual(`AB`); }); it('should copy injector information unto placeholder', () => { // This test demonstrates an issue with i18n Placeholders loosing `injectorIndex` information. // NOTE: This test is extracted from g3. @Component({ template: ` <parent i18n> <middle> <child>Text</child> </middle> </parent>`, standalone: false, }) class MyApp {} @Component({ selector: 'parent', standalone: false, }) class Parent {} @Component({ selector: 'middle', standalone: false, }) class Middle {} @Component({ selector: 'child', standalone: false, }) class Child { constructor(public middle: Middle) { child = this; } } let child: Child | undefined; TestBed.configureTestingModule({declarations: [MyApp, Parent, Middle, Child]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(child?.middle).toBeInstanceOf(Middle); }); it('should allow container in gotClosestRElement', () => { // A second iteration of the loop will have `Container` `TNode`s pass through the system. // NOTE: This test is extracted from g3. @Component({ template: ` <div *ngFor="let i of [1,2]"> <ng-template #tmpl i18n><span *ngIf="true">X</span></ng-template> <span [ngTemplateOutlet]="tmpl"></span> </div>`, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual(`XX`); }); it('should link text after ICU', () => { // i18n block must restore the current `currentTNode` so that trailing text node can link to it. // NOTE: This test is extracted from g3. @Component({ template: ` <ng-container *ngFor="let index of [1, 2]"> {{'['}} {index, plural, =1 {1} other {*}} {index, plural, =1 {one} other {many}} {{'-'}} <span>+</span> {{'-'}} {index, plural, =1 {first} other {rest}} {{']'}} </ng-container> / <ng-container *ngFor="let index of [1, 2]" i18n> {{'['}} {index, plural, =1 {1} other {*}} {index, plural, =1 {one} other {many}} {{'-'}} <span>+</span> {{'-'}} {index, plural, =1 {first} other {rest}} {{']'}} </ng-container> `, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const textContent = fixture.nativeElement.textContent as string; expect(textContent.split('/').map((s) => s.trim())).toEqual([ '[ 1 one - + - first ] [ * many - + - rest ]', '[ 1 one - + - first ] [ * many - + - rest ]', ]); }); it('should ignore non-instantiated ICUs on update', () => { // Demonstrates an issue of same selector expression used in nested ICUs, causes non // instantiated nested ICUs to be updated. // NOTE: This test is extracted from g3. @Component({ template: ` before| { retention.unit, select, SECONDS { {retention.durationInUnits, plural, =1 {1 second} other {{{retention.durationInUnits}} seconds} } } DAYS { {retention.durationInUnits, plural, =1 {1 day} other {{{retention.durationInUnits}} days} } } MONTHS { {retention.durationInUnits, plural, =1 {1 month} other {{{retention.durationInUnits}} months} } } YEARS { {retention.durationInUnits, plural, =1 {1 year} other {{{retention.durationInUnits}} years} } } other {} } |after. `, standalone: false, }) class MyApp { retention = { durationInUnits: 10, unit: 'SECONDS', }; } TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const textContent = fixture.nativeElement.textContent as string; expect(textContent.replace(/\s+/g, ' ').trim()).toEqual(`before| 10 seconds |after.`); }); it('should render attributes defined in ICUs', () => { // NOTE: This test is extracted from g3. @Component({ template: ` <div i18n>{ parameters.length, plural, =1 {Affects parameter <span class="parameter-name" attr="should_be_present">{{parameters[0].name}}</span>} other {Affects {{parameters.length}} parameters, including <span class="parameter-name">{{parameters[0].name}}</span>} }</div> `, standalone: false, }) class MyApp { parameters = [{name: 'void_abt_param'}]; } TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const span = (fixture.nativeElement as HTMLElement).querySelector('span')!; expect(span.getAttribute('attr')).toEqual('should_be_present'); expect(span.getAttribute('class')).toEqual('parameter-name'); }); it('should support different ICUs cases for eac
{ "end_byte": 120627, "start_byte": 112612, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/i18n_spec.ts_120631_124403
gFor iteration', () => { @Component({ template: ` <ul i18n> <li *ngFor="let item of items">{ item, plural, =1 {<b>one</b>} =2 {<i>two</i>} },</li> </ul>`, standalone: false, }) class MyApp { items = [1, 2]; } TestBed.configureTestingModule({declarations: [MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual(`one,two,`); fixture.componentInstance.items = [2, 1]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual(`two,one,`); }); it('should be able to inject a static i18n attribute', () => { loadTranslations({[computeMsgId('text')]: 'translatedText'}); @Directive({ selector: '[injectTitle]', standalone: false, }) class InjectTitleDir { constructor(@Attribute('title') public title: string) {} } @Component({ template: `<div i18n-title title="text" injectTitle></div>`, standalone: false, }) class App { @ViewChild(InjectTitleDir) dir!: InjectTitleDir; } TestBed.configureTestingModule({declarations: [App, InjectTitleDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.dir.title).toBe('translatedText'); expect(fixture.nativeElement.querySelector('div').getAttribute('title')).toBe('translatedText'); }); it('should inject `null` for an i18n attribute with an interpolation', () => { loadTranslations({[computeMsgId('text {$INTERPOLATION}')]: 'translatedText {$INTERPOLATION}'}); @Directive({ selector: '[injectTitle]', standalone: false, }) class InjectTitleDir { constructor(@Attribute('title') public title: string) {} } @Component({ template: `<div i18n-title title="text {{ value }}" injectTitle></div>`, standalone: false, }) class App { @ViewChild(InjectTitleDir) dir!: InjectTitleDir; value = 'value'; } TestBed.configureTestingModule({declarations: [App, InjectTitleDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.dir.title).toBeNull(); expect(fixture.nativeElement.querySelector('div').getAttribute('title')).toBe( 'translatedText value', ); }); }); function initWithTemplate(compType: Type<any>, template: string) { TestBed.overrideComponent(compType, {set: {template}}); const fixture = TestBed.createComponent(compType); fixture.detectChanges(); return fixture; } @Component({ selector: 'app-comp', template: ``, standalone: false, }) class AppComp { name = `Angular`; description = `Web Framework`; visible = true; count = 0; items = [1, 2, 3]; } @Component({ selector: 'app-comp-with-whitespaces', template: ``, preserveWhitespaces: true, standalone: false, }) class AppCompWithWhitespaces {} @Directive({ selector: '[tplRef]', standalone: false, }) class DirectiveWithTplRef { constructor( public vcRef: ViewContainerRef, public tplRef: TemplateRef<{}>, ) {} ngOnInit() { this.vcRef.createEmbeddedView(this.tplRef, {}); } } @Pipe({ name: 'uppercase', standalone: false, }) class UppercasePipe implements PipeTransform { transform(value: string) { return value.toUpperCase(); } } @Directive({ selector: `[dialog]`, standalone: false, }) export class DialogDir {} @Directive({ selector: `button[close]`, host: {'[title]': 'name'}, standalone: false, }) export class CloseBtn { @Input('close') dialogResult: any; name: string = 'Close dialog'; }
{ "end_byte": 124403, "start_byte": 120631, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/i18n_spec.ts" }
angular/packages/core/test/acceptance/control_flow_if_spec.ts_0_8570
/** * @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 {NgFor} from '@angular/common'; import { ChangeDetectorRef, Component, Directive, inject, Input, OnInit, Pipe, PipeTransform, TemplateRef, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; // Basic shared pipe used during testing. @Pipe({name: 'multiply', pure: true, standalone: true}) class MultiplyPipe implements PipeTransform { transform(value: number, amount: number) { return value * amount; } } describe('control flow - if', () => { it('should add and remove views based on conditions change', () => { @Component({standalone: true, template: '@if (show) {Something} @else {Nothing}'}) class TestComponent { show = true; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Something'); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Nothing'); }); it('should expose expression value in context', () => { @Component({ standalone: true, template: '@if (show; as alias) {{{show}} aliased to {{alias}}}', }) class TestComponent { show: any = true; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('true aliased to true'); fixture.componentInstance.show = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1 aliased to 1'); }); it('should not expose the aliased expression to `if` and `else if` blocks', () => { @Component({ standalone: true, template: ` @if (value === 1; as alias) { If: {{value}} as {{alias || 'unavailable'}} } @else if (value === 2) { ElseIf: {{value}} as {{alias || 'unavailable'}} } @else { Else: {{value}} as {{alias || 'unavailable'}} } `, }) class TestComponent { value = 1; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('If: 1 as true'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('ElseIf: 2 as unavailable'); fixture.componentInstance.value = 3; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Else: 3 as unavailable'); }); it('should expose the context to nested conditional blocks', () => { @Component({ standalone: true, imports: [MultiplyPipe], template: ` @if (value | multiply:2; as root) { Root: {{value}}/{{root}} @if (value | multiply:3; as inner) { Inner: {{value}}/{{root}}/{{inner}} @if (value | multiply:4; as innermost) { Innermost: {{value}}/{{root}}/{{inner}}/{{innermost}} } } } `, }) class TestComponent { value = 1; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); let content = fixture.nativeElement.textContent; expect(content).toContain('Root: 1/2'); expect(content).toContain('Inner: 1/2/3'); expect(content).toContain('Innermost: 1/2/3/4'); fixture.componentInstance.value = 2; fixture.detectChanges(); content = fixture.nativeElement.textContent; expect(content).toContain('Root: 2/4'); expect(content).toContain('Inner: 2/4/6'); expect(content).toContain('Innermost: 2/4/6/8'); }); it('should expose the context to listeners inside nested conditional blocks', () => { let logs: any[] = []; @Component({ standalone: true, imports: [MultiplyPipe], template: ` @if (value | multiply:2; as root) { <button (click)="log(['Root', value, root])"></button> @if (value | multiply:3; as inner) { <button (click)="log(['Inner', value, root, inner])"></button> @if (value | multiply:4; as innermost) { <button (click)="log(['Innermost', value, root, inner, innermost])"></button> } } } `, }) class TestComponent { value = 1; log(value: any) { logs.push(value); } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const buttons = Array.from<HTMLButtonElement>(fixture.nativeElement.querySelectorAll('button')); buttons.forEach((button) => button.click()); fixture.detectChanges(); expect(logs).toEqual([ ['Root', 1, 2], ['Inner', 1, 2, 3], ['Innermost', 1, 2, 3, 4], ]); logs = []; fixture.componentInstance.value = 2; fixture.detectChanges(); buttons.forEach((button) => button.click()); fixture.detectChanges(); expect(logs).toEqual([ ['Root', 2, 4], ['Inner', 2, 4, 6], ['Innermost', 2, 4, 6, 8], ]); }); it('should expose expression value passed through a pipe in context', () => { @Component({ standalone: true, template: '@if (value | multiply:2; as alias) {{{value}} aliased to {{alias}}}', imports: [MultiplyPipe], }) class TestComponent { value = 1; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1 aliased to 2'); fixture.componentInstance.value = 4; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('4 aliased to 8'); }); it('should destroy all views if there is nothing to display', () => { @Component({ standalone: true, template: '@if (show) {Something}', }) class TestComponent { show = true; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Something'); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); }); it('should be able to use pipes in conditional expressions', () => { @Component({ standalone: true, imports: [MultiplyPipe], template: ` @if ((value | multiply:2) === 2) { one } @else if ((value | multiply:2) === 4) { two } @else { nothing } `, }) class TestComponent { value = 0; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('nothing'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('two'); fixture.componentInstance.value = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('one'); }); it('should be able to use pipes injecting ChangeDetectorRef in if blocks', () => { @Pipe({name: 'test', standalone: true}) class TestPipe implements PipeTransform { changeDetectorRef = inject(ChangeDetectorRef); transform(value: any) { return value; } } @Component({ standalone: true, template: '@if (show | test) {Something}', imports: [TestPipe], }) class TestComponent { show = true; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Something'); }); it('should support a condition with the a typeof expression', () => { @Component({ standalone: true, template: ` @if (typeof value === 'string') { {{value.length}} } @else { {{value}} } `, }) class TestComponent { value: string | number = 'string'; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('6'); fixture.componentInstance.value = 42; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('42'); });
{ "end_byte": 8570, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_if_spec.ts" }
angular/packages/core/test/acceptance/control_flow_if_spec.ts_8574_17615
describe('content projection', () => { it('should project an @if with a single root node into the root node slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @if (true) { <span foo>foo</span> } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: foo'); }); it('should project an @if with a single root node with a data binding', () => { let directiveCount = 0; @Directive({standalone: true, selector: '[foo]'}) class Foo { @Input('foo') value: any; constructor() { directiveCount++; } } @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent, Foo], template: ` <test>Before @if (true) { <span [foo]="value">foo</span> } After</test> `, }) class App { value = 1; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: foo'); expect(directiveCount).toBe(1); }); it('should project an @if with multiple root nodes into the catch-all slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @if (true) { <span foo>one</span> <div foo>two</div> } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before onetwo After Slot: '); }); it('should project an @if with an ng-container root node', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @if (true) { <ng-container foo> <span>foo</span> <span>bar</span> </ng-container> } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: foobar'); }); // Right now the template compiler doesn't collect comment nodes. // This test is to ensure that we don't regress if it happens in the future. it('should project an @if with a single root node and comments into the root node slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @if (true) { <!-- before --> <span foo>foo</span> <!-- after --> } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: foo'); }); it('should project @if an @else content into separate slots', () => { @Component({ standalone: true, selector: 'test', template: 'if: (<ng-content select="[if_case]"/>), else: (<ng-content select="[else_case]"/>)', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test> @if (value) { <span if_case>if content</span> } @else { <span else_case>else content</span> } </test> `, }) class App { value = true; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (if content), else: ()'); fixture.componentInstance.value = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (), else: (else content)'); fixture.componentInstance.value = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (if content), else: ()'); }); it('should project @if an @else content into separate slots when if has default content', () => { @Component({ standalone: true, selector: 'test', template: 'if: (<ng-content />), else: (<ng-content select="[else_case]"/>)', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test> @if (value) { <span>if content</span> } @else { <span else_case>else content</span> } </test> `, }) class App { value = true; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (if content), else: ()'); fixture.componentInstance.value = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (), else: (else content)'); fixture.componentInstance.value = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (if content), else: ()'); }); it('should project @if an @else content into separate slots when else has default content', () => { @Component({ standalone: true, selector: 'test', template: 'if: (<ng-content select="[if_case]"/>), else: (<ng-content/>)', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test> @if (value) { <span if_case>if content</span> } @else { <span>else content</span> } </test> `, }) class App { value = true; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (if content), else: ()'); fixture.componentInstance.value = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (), else: (else content)'); fixture.componentInstance.value = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('if: (if content), else: ()'); }); it('should project the root node when preserveWhitespaces is enabled and there are no whitespace nodes', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], preserveWhitespaces: true, template: '<test>Before @if (true) {<span foo>one</span>} After</test>', }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: one'); }); it('should not project the root node when preserveWhitespaces is enabled and there are whitespace nodes', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], preserveWhitespaces: true, // Note the whitespace due to the indentation inside @if. template: ` <test>Before @if (true) { <span foo>one</span> } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toMatch(/Main: Before\s+one\s+After Slot:/); });
{ "end_byte": 17615, "start_byte": 8574, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_if_spec.ts" }
angular/packages/core/test/acceptance/control_flow_if_spec.ts_17621_23920
it('should not project the root node across multiple layers of @if', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @if (true) { @if (true) { <span foo>one</span> } } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toMatch(/Main: Before\s+one\s+After Slot:/); }); it('should project an @if with a single root template node into the root node slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent, NgFor], template: `<test>Before @if (true) { <span *ngFor="let item of items" foo>{{item}}</span> } After</test>`, }) class App { items = [1, 2]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 12'); fixture.componentInstance.items.push(3); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 123'); }); it('should invoke a projected attribute directive at the root of an @if once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[foo]', standalone: true, }) class FooDirective { constructor() { directiveCount++; } } @Component({ standalone: true, imports: [TestComponent, FooDirective], template: `<test>Before @if (true) { <span foo>foo</span> } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: foo'); }); it('should invoke a projected template directive at the root of an @if once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[templateDir]', standalone: true, }) class TemplateDirective implements OnInit { constructor( private viewContainerRef: ViewContainerRef, private templateRef: TemplateRef<any>, ) { directiveCount++; } ngOnInit(): void { const view = this.viewContainerRef.createEmbeddedView(this.templateRef); this.viewContainerRef.insert(view); } } @Component({ standalone: true, imports: [TestComponent, TemplateDirective], template: `<test>Before @if (true) { <span *templateDir foo>foo</span> } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: foo'); }); it('should invoke a directive on a projected ng-template at the root of an @if once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[templateDir]', standalone: true, }) class TemplateDirective implements OnInit { constructor( private viewContainerRef: ViewContainerRef, private templateRef: TemplateRef<any>, ) { directiveCount++; } ngOnInit(): void { const view = this.viewContainerRef.createEmbeddedView(this.templateRef); this.viewContainerRef.insert(view); } } @Component({ standalone: true, imports: [TestComponent, TemplateDirective], template: `<test>Before @if (true) { <ng-template templateDir foo>foo</ng-template> } After</test> `, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: foo'); }); it('should not match a directive with a class-based selector only meant for content projection', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select=".foo"/>', }) class TestComponent {} @Directive({ selector: '.foo', standalone: true, }) class TemplateDirective { constructor() { directiveCount++; } } @Component({ standalone: true, imports: [TestComponent, TemplateDirective], template: `<test>Before @if (condition) { <div class="foo">foo</div> } After</test> `, }) class App { condition = false; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(0); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: '); fixture.componentInstance.condition = true; fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: foo'); }); }); });
{ "end_byte": 23920, "start_byte": 17621, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_if_spec.ts" }
angular/packages/core/test/acceptance/control_flow_for_spec.ts_0_5906
/** * @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 {NgIf} from '@angular/common'; import { ChangeDetectorRef, Component, Directive, inject, Input, OnInit, Pipe, PipeTransform, TemplateRef, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('control flow - for', () => { it('should create, remove and move views corresponding to items in a collection', () => { @Component({ template: '@for ((item of items); track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); fixture.componentInstance.items.pop(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|'); fixture.componentInstance.items.push(3); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); fixture.componentInstance.items[0] = 3; fixture.componentInstance.items[2] = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('3(0)|2(1)|1(2)|'); }); it('should loop over iterators that can be iterated over only once', () => { @Component({ template: '@for ((item of items.keys()); track $index) {{{item}}|}', standalone: false, }) class TestComponent { items = new Map([ ['a', 1], ['b', 2], ['c', 3], ]); } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('a|b|c|'); }); it('should work correctly with trackBy index', () => { @Component({ template: '@for ((item of items); track idx; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); fixture.componentInstance.items.pop(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|'); fixture.componentInstance.items.push(3); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); fixture.componentInstance.items[0] = 3; fixture.componentInstance.items[2] = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('3(0)|2(1)|1(2)|'); }); it('should support empty blocks', () => { @Component({ template: '@for ((item of items); track idx; let idx = $index) {|} @empty {Empty}', standalone: false, }) class TestComponent { items: number[] | null | undefined = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|||'); fixture.componentInstance.items = []; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Empty'); fixture.componentInstance.items = [0, 1]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('||'); fixture.componentInstance.items = null; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Empty'); fixture.componentInstance.items = [0]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|'); fixture.componentInstance.items = undefined; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Empty'); }); it('should be able to use pipes injecting ChangeDetectorRef in for loop blocks', () => { @Pipe({name: 'test', standalone: true}) class TestPipe implements PipeTransform { changeDetectorRef = inject(ChangeDetectorRef); transform(value: any) { return value; } } @Component({ template: '@for (item of items | test; track item;) {{{item}}|}', imports: [TestPipe], standalone: true, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1|2|3|'); }); it('should be able to access a directive property that is reassigned in a lifecycle hook', () => { @Directive({ selector: '[dir]', exportAs: 'dir', standalone: true, }) class Dir { data = [1]; ngDoCheck() { this.data = [2]; } } @Component({ selector: 'app-root', standalone: true, imports: [Dir], template: ` <div [dir] #dir="dir"></div> @for (x of dir.data; track $index) { {{x}} } `, }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('2'); }); it('should expose variables both under their real names and aliases', () => { @Component({ template: '@for ((item of items); track item; let idx = $index) {{{item}}({{$index}}/{{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0/0)|2(1/1)|3(2/2)|'); fixture.componentInstance.items.splice(1, 1); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0/0)|3(1/1)|'); });
{ "end_byte": 5906, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_for_spec.ts" }
angular/packages/core/test/acceptance/control_flow_for_spec.ts_5910_15310
describe('trackBy', () => { it('should have access to the host context in the track function', () => { let offsetReads = 0; @Component({ template: '@for ((item of items); track $index + offset) {{{item}}}', standalone: false, }) class TestComponent { items = ['a', 'b', 'c']; get offset() { offsetReads++; return 0; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('abc'); expect(offsetReads).toBeGreaterThan(0); const prevReads = offsetReads; // explicitly modify the DOM text node to make sure that the list reconciliation algorithm // based on tracking indices overrides it. fixture.debugElement.childNodes[1].nativeNode.data = 'x'; fixture.componentInstance.items.shift(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('bc'); expect(offsetReads).toBeGreaterThan(prevReads); }); it('should be able to access component properties in the tracking function from a loop at the root of the template', () => { const calls = new Set(); @Component({ template: `@for ((item of items); track trackingFn(item, compProp)) {{{item}}}`, standalone: false, }) class TestComponent { items = ['a', 'b']; compProp = 'hello'; trackingFn(item: string, message: string) { calls.add(`${item}:${message}`); return item; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect([...calls].sort()).toEqual(['a:hello', 'b:hello']); }); it('should be able to access component properties in the tracking function from a nested template', () => { const calls = new Set(); @Component({ template: ` @if (true) { @if (true) { @if (true) { @for ((item of items); track trackingFn(item, compProp)) {{{item}}} } } } `, standalone: false, }) class TestComponent { items = ['a', 'b']; compProp = 'hello'; trackingFn(item: string, message: string) { calls.add(`${item}:${message}`); return item; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect([...calls].sort()).toEqual(['a:hello', 'b:hello']); }); it('should invoke method tracking function with the correct context', () => { let context = null as TestComponent | null; @Component({ template: `@for (item of items; track trackingFn($index, item)) {{{item}}}`, standalone: false, }) class TestComponent { items = ['a', 'b']; trackingFn(_index: number, item: string) { context = this; return item; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(context).toBe(fixture.componentInstance); }); it('should warn about duplicated keys when using arrays', () => { @Component({ template: `@for (item of items; track item) {{{item}}}`, standalone: false, }) class TestComponent { items = ['a', 'b', 'a', 'c', 'a']; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('abaca'); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( `NG0955: The provided track expression resulted in duplicated keys for a given collection.`, ), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( `Adjust the tracking expression such that it uniquely identifies all the items in the collection. `, ), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`key "a" at index "0" and "2"`), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`key "a" at index "2" and "4"`), ); }); it('should warn about duplicated keys when using iterables', () => { @Component({ template: `@for (item of items.values(); track item) {{{item}}}`, standalone: false, }) class TestComponent { items = new Map([ [1, 'a'], [2, 'b'], [3, 'a'], [4, 'c'], [5, 'a'], ]); } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('abaca'); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( `NG0955: The provided track expression resulted in duplicated keys for a given collection.`, ), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( `Adjust the tracking expression such that it uniquely identifies all the items in the collection. `, ), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`key "a" at index "0" and "2"`), ); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`key "a" at index "2" and "4"`), ); }); it('should warn about duplicate keys when keys are expressed as symbols', () => { const value = Symbol('a'); @Component({ template: `@for (item of items.values(); track item) {}`, standalone: false, }) class TestComponent { items = new Map([ [1, value], [2, value], ]); } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining(`Symbol(a)" at index "0" and "1".`), ); }); it('should not warn about duplicate keys iterating over the new collection only', () => { @Component({ template: `@for (item of items; track item) {}`, standalone: false, }) class TestComponent { items = [1, 2, 3]; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(console.warn).not.toHaveBeenCalled(); fixture.componentInstance.items = [4, 5, 6]; fixture.detectChanges(); expect(console.warn).not.toHaveBeenCalled(); }); it('should warn about collection re-creation due to identity tracking', () => { @Component({ template: `@for (item of items; track item) {(<span>{{item.value}}</span>)}`, standalone: false, }) class TestComponent { items = [{value: 0}, {value: 1}]; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)(1)'); expect(console.warn).not.toHaveBeenCalled(); fixture.componentInstance.items = fixture.componentInstance.items.map((item) => ({ value: item.value + 1, })); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(1)(2)'); expect(console.warn).toHaveBeenCalled(); }); it('should NOT warn about collection re-creation when a view is not considered expensive', () => { @Component({ template: `@for (item of items; track item) {({{item.value}})}`, standalone: false, }) class TestComponent { items = [{value: 0}, {value: 1}]; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)(1)'); expect(console.warn).not.toHaveBeenCalled(); fixture.componentInstance.items = fixture.componentInstance.items.map((item) => ({ value: item.value + 1, })); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(1)(2)'); expect(console.warn).not.toHaveBeenCalled(); }); it('should NOT warn about collection re-creation when a trackBy function is not identity', () => { @Component({ template: `@for (item of items; track item.value) {({{item.value}})}`, standalone: false, }) class TestComponent { items = [{value: 0}, {value: 1}]; } spyOn(console, 'warn'); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)(1)'); expect(console.warn).not.toHaveBeenCalled(); fixture.componentInstance.items = fixture.componentInstance.items.map((item) => ({ value: item.value + 1, })); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(1)(2)'); expect(console.warn).not.toHaveBeenCalled(); }); });
{ "end_byte": 15310, "start_byte": 5910, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_for_spec.ts" }
angular/packages/core/test/acceptance/control_flow_for_spec.ts_15314_19100
describe('list diffing and view operations', () => { it('should delete views in the middle', () => { @Component({ template: '@for (item of items; track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); // delete in the middle fixture.componentInstance.items.splice(1, 1); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|3(1)|'); }); it('should insert views in the middle', () => { @Component({ template: '@for (item of items; track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|3(1)|'); // add in the middle fixture.componentInstance.items.splice(1, 0, 2); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); }); it('should replace different items', () => { @Component({ template: '@for (item of items; track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|'); // an item in the middle stays the same, the rest gets replaced fixture.componentInstance.items = [5, 2, 7]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('5(0)|2(1)|7(2)|'); }); it('should move and delete items', () => { @Component({ template: '@for (item of items; track item; let idx = $index) {{{item}}({{idx}})|}', standalone: false, }) class TestComponent { items = [1, 2, 3, 4, 5, 6]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(false); expect(fixture.nativeElement.textContent).toBe('1(0)|2(1)|3(2)|4(3)|5(4)|6(5)|'); // move 5 and do some other delete other operations fixture.componentInstance.items = [5, 3, 7]; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('5(0)|3(1)|7(2)|'); }); it('should correctly attach and detach views with duplicated keys', () => { const BEFORE = [ {'name': 'Task 14', 'id': 14}, {'name': 'Task 14', 'id': 14}, {'name': 'Task 70', 'id': 70}, {'name': 'Task 34', 'id': 34}, ]; const AFTER = [ {'name': 'Task 70', 'id': 70}, {'name': 'Task 14', 'id': 14}, {'name': 'Task 28', 'id': 28}, ]; @Component({ standalone: true, template: ``, selector: 'child-cmp', }) class ChildCmp {} @Component({ standalone: true, imports: [ChildCmp], template: ` @for(task of tasks; track task.id) { <child-cmp/> } `, }) class TestComponent { tasks = BEFORE; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const cmp = fixture.componentInstance; const nativeElement = fixture.debugElement.nativeElement; cmp.tasks = AFTER; fixture.detectChanges(); expect(nativeElement.querySelectorAll('child-cmp').length).toBe(3); }); });
{ "end_byte": 19100, "start_byte": 15314, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_for_spec.ts" }
angular/packages/core/test/acceptance/control_flow_for_spec.ts_19104_27047
describe('content projection', () => { it('should project an @for with a single root node into the root node slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @for (item of items; track $index) { <span foo>{{item}}</span> } After</test> `, }) class App { items = [1, 2, 3]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 123'); }); it('should project an @empty block with a single root node into the root node slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @for (item of items; track $index) {} @empty { <span foo>Empty</span> } After</test> `, }) class App { items = []; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: Empty'); }); it('should allow @for and @empty blocks to be projected into different slots', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Loop slot: <ng-content select="[loop]"/> Empty slot: <ng-content select="[empty]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @for (item of items; track $index) { <span loop>{{item}}</span> } @empty { <span empty>Empty</span> } After</test> `, }) class App { items = [1, 2, 3]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe( 'Main: Before After Loop slot: 123 Empty slot: ', ); fixture.componentInstance.items = []; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe( 'Main: Before After Loop slot: Empty slot: Empty', ); }); it('should project an @for with multiple root nodes into the catch-all slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @for (item of items; track $index) { <span foo>one{{item}}</span> <div foo>two{{item}}</div> } After</test> `, }) class App { items = [1, 2]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before one1two1one2two2 After Slot: '); }); it('should project an @for with a single root node with a data binding', () => { let directiveCount = 0; @Directive({standalone: true, selector: '[foo]'}) class Foo { @Input('foo') value: any; constructor() { directiveCount++; } } @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent, Foo], template: ` <test>Before @for (item of items; track $index) { <span [foo]="item">{{item}}</span> } After</test> `, }) class App { items = [1, 2, 3]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 123'); expect(directiveCount).toBe(3); }); it('should project an @for with an ng-container root node', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @for (item of items; track $index) { <ng-container foo> <span>{{item}}</span> <span>|</span> </ng-container> } After</test> `, }) class App { items = [1, 2, 3]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 1|2|3|'); }); // Right now the template compiler doesn't collect comment nodes. // This test is to ensure that we don't regress if it happens in the future. it('should project an @for with single root node and comments into the root node slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @for (item of items; track $index) { <!-- before --> <span foo>{{item}}</span> <!-- after --> } After</test> `, }) class App { items = [1, 2, 3]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 123'); }); it('should project the root node when preserveWhitespaces is enabled and there are no whitespace nodes', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], preserveWhitespaces: true, // Note the whitespace due to the indentation inside @for. template: '<test>Before @for (item of items; track $index) {<span foo>{{item}}</span>} After</test>', }) class App { items = [1, 2, 3]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 123'); }); it('should not project the root node when preserveWhitespaces is enabled and there are whitespace nodes', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], preserveWhitespaces: true, // Note the whitespace due to the indentation inside @for. template: ` <test>Before @for (item of items; track $index) { <span foo>{{item}}</span> } After</test> `, }) class App { items = [1, 2, 3]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toMatch(/Main: Before\s+1\s+2\s+3\s+After Slot:/); });
{ "end_byte": 27047, "start_byte": 19104, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_for_spec.ts" }
angular/packages/core/test/acceptance/control_flow_for_spec.ts_27053_32399
it('should not project the root node across multiple layers of @for', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent], template: ` <test>Before @for (item of items; track $index) { @for (item of items; track $index) { <span foo>{{item}}</span> } } After</test> `, }) class App { items = [1, 2]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before 1212 After Slot: '); }); it('should project an @for with a single root template node into the root node slot', () => { @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Component({ standalone: true, imports: [TestComponent, NgIf], template: `<test>Before @for (item of items; track $index) { <span *ngIf="true" foo>{{item}}</span> } After</test>`, }) class App { items = [1, 2]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 12'); fixture.componentInstance.items.push(3); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 123'); }); it('should invoke a projected attribute directive at the root of an @for once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[foo]', standalone: true, }) class FooDirective { constructor() { directiveCount++; } } @Component({ standalone: true, imports: [TestComponent, FooDirective], template: `<test>Before @for (item of items; track $index) { <span foo>{{item}}</span> } After</test> `, }) class App { items = [1]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 1'); }); it('should invoke a projected template directive at the root of an @for once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[templateDir]', standalone: true, }) class TemplateDirective implements OnInit { constructor( private viewContainerRef: ViewContainerRef, private templateRef: TemplateRef<any>, ) { directiveCount++; } ngOnInit(): void { const view = this.viewContainerRef.createEmbeddedView(this.templateRef); this.viewContainerRef.insert(view); } } @Component({ standalone: true, imports: [TestComponent, TemplateDirective], template: `<test>Before @for (item of items; track $index) { <span *templateDir foo>{{item}}</span> } After</test> `, }) class App { items = [1]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 1'); }); it('should invoke a directive on a projected ng-template at the root of an @for once', () => { let directiveCount = 0; @Component({ standalone: true, selector: 'test', template: 'Main: <ng-content/> Slot: <ng-content select="[foo]"/>', }) class TestComponent {} @Directive({ selector: '[templateDir]', standalone: true, }) class TemplateDirective implements OnInit { constructor( private viewContainerRef: ViewContainerRef, private templateRef: TemplateRef<any>, ) { directiveCount++; } ngOnInit(): void { const view = this.viewContainerRef.createEmbeddedView(this.templateRef); this.viewContainerRef.insert(view); } } @Component({ standalone: true, imports: [TestComponent, TemplateDirective], template: `<test>Before @for (item of items; track $index) { <ng-template templateDir foo>{{item}}</ng-template> } After</test> `, }) class App { items = [1]; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(directiveCount).toBe(1); expect(fixture.nativeElement.textContent).toBe('Main: Before After Slot: 1'); }); }); });
{ "end_byte": 32399, "start_byte": 27053, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_for_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_0_7557
/** * @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 {CommonModule} from '@angular/common'; import { AfterViewInit, ChangeDetectorRef, Component, ContentChildren, Directive, DoCheck, Input, NgModule, OnChanges, QueryList, SimpleChange, SimpleChanges, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('onChanges', () => { it('should correctly support updating one Input among many', () => { let log: string[] = []; @Component({ selector: 'child-comp', template: 'child', standalone: false, }) class ChildComp implements OnChanges { @Input() a: number = 0; @Input() b: number = 0; @Input() c: number = 0; ngOnChanges(changes: SimpleChanges) { for (let key in changes) { const simpleChange = changes[key]; log.push(key + ': ' + simpleChange.previousValue + ' -> ' + simpleChange.currentValue); } } } @Component({ selector: 'app-comp', template: '<child-comp [a]="a" [b]="b" [c]="c"></child-comp>', standalone: false, }) class AppComp { a = 0; b = 0; c = 0; } TestBed.configureTestingModule({declarations: [AppComp, ChildComp]}); const fixture = TestBed.createComponent(AppComp); fixture.detectChanges(); const appComp = fixture.componentInstance; expect(log).toEqual(['a: undefined -> 0', 'b: undefined -> 0', 'c: undefined -> 0']); log.length = 0; appComp.a = 1; fixture.detectChanges(); expect(log).toEqual(['a: 0 -> 1']); log.length = 0; appComp.b = 2; fixture.detectChanges(); expect(log).toEqual(['b: 0 -> 2']); log.length = 0; appComp.c = 3; fixture.detectChanges(); expect(log).toEqual(['c: 0 -> 3']); }); it('should call onChanges method after inputs are set in creation and update mode', () => { const events: any[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() val1 = 'a'; @Input('publicVal2') val2 = 'b'; ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } } @Component({ template: `<comp [val1]="val1" [publicVal2]="val2"></comp>`, standalone: false, }) class App { val1 = 'a2'; val2 = 'b2'; } TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val1: new SimpleChange(undefined, 'a2', true), val2: new SimpleChange(undefined, 'b2', true), }, }, ]); events.length = 0; fixture.componentInstance.val1 = 'a3'; fixture.componentInstance.val2 = 'b3'; fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val1: new SimpleChange('a2', 'a3', false), val2: new SimpleChange('b2', 'b3', false), }, }, ]); }); it('should call parent onChanges before child onChanges', () => { const events: any[] = []; @Component({ selector: 'parent', template: `<child [val]="val"></child>`, standalone: false, }) class Parent { @Input() val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent', changes}); } } @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'child', changes}); } } @Component({ template: `<parent [val]="val"></parent>`, standalone: false, }) class App { val = 'foo'; } TestBed.configureTestingModule({ declarations: [App, Child, Parent], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'parent', changes: { val: new SimpleChange(undefined, 'foo', true), }, }, { name: 'child', changes: { val: new SimpleChange(undefined, 'foo', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'bar'; fixture.detectChanges(); expect(events).toEqual([ { name: 'parent', changes: { val: new SimpleChange('foo', 'bar', false), }, }, { name: 'child', changes: { val: new SimpleChange('foo', 'bar', false), }, }, ]); }); it('should call all parent onChanges across view before calling children onChanges', () => { const events: any[] = []; @Component({ selector: 'parent', template: `<child [name]="name" [val]="val"></child>`, standalone: false, }) class Parent { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent ' + this.name, changes}); } } @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'child ' + this.name, changes}); } } @Component({ template: ` <parent name="1" [val]="val"></parent> <parent name="2" [val]="val"></parent> `, standalone: false, }) class App { val = 'foo'; } TestBed.configureTestingModule({ declarations: [App, Child, Parent], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'parent 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'foo', true), }, }, { name: 'parent 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'foo', true), }, }, { name: 'child 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'foo', true), }, }, { name: 'child 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'foo', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'bar'; fixture.detectChanges(); expect(events).toEqual([ { name: 'parent 1', changes: { val: new SimpleChange('foo', 'bar', false), }, }, { name: 'parent 2', changes: { val: new SimpleChange('foo', 'bar', false), }, }, { name: 'child 1', changes: { val: new SimpleChange('foo', 'bar', false), }, }, { name: 'child 2', changes: { val: new SimpleChange('foo', 'bar', false), }, }, ]); });
{ "end_byte": 7557, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_7561_14719
it('should call onChanges every time a new view is created with ngIf', () => { const events: any[] = []; @Component({ selector: 'comp', template: `<p>{{val}}</p>`, standalone: false, }) class Comp { @Input() val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } } @Component({ template: `<comp *ngIf="show" [val]="val"></comp>`, standalone: false, }) class App { show = true; val = 'a'; } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val: new SimpleChange(undefined, 'a', true), }, }, ]); events.length = 0; fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.val = 'b'; fixture.componentInstance.show = true; fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val: new SimpleChange(undefined, 'b', true), }, }, ]); }); it('should call onChanges in hosts before their content children', () => { const events: any[] = []; @Component({ selector: 'projected', template: `<p>{{val}}</p>`, standalone: false, }) class Projected { @Input() val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'projected', changes}); } } @Component({ selector: 'comp', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Comp { @Input() val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } } @Component({ template: `<comp [val]="val"><projected [val]="val"></projected></comp>`, standalone: false, }) class App { val = 'a'; } TestBed.configureTestingModule({ declarations: [App, Comp, Projected], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val: new SimpleChange(undefined, 'a', true), }, }, { name: 'projected', changes: { val: new SimpleChange(undefined, 'a', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'b'; fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'projected', changes: { val: new SimpleChange('a', 'b', false), }, }, ]); }); it('should call onChanges in host and its content children before next host', () => { const events: any[] = []; @Component({ selector: 'projected', template: `<p>{{val}}</p>`, standalone: false, }) class Projected { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'projected ' + this.name, changes}); } } @Component({ selector: 'comp', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Comp { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp ' + this.name, changes}); } } @Component({ template: ` <comp name="1" [val]="val"> <projected name="1" [val]="val"></projected> </comp> <comp name="2" [val]="val"> <projected name="2" [val]="val"></projected> </comp> `, standalone: false, }) class App { val = 'a'; } TestBed.configureTestingModule({ declarations: [App, Comp, Projected], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'comp 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'projected 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'comp 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'projected 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'a', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'b'; fixture.detectChanges(); expect(events).toEqual([ { name: 'comp 1', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'projected 1', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'comp 2', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'projected 2', changes: { val: new SimpleChange('a', 'b', false), }, }, ]); }); it('should be called on directives after component by default', () => { const events: any[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input() dir = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'dir', changes}); } } @Component({ selector: 'comp', template: `<p>{{val}}</p>`, standalone: false, }) class Comp { @Input() val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } } @Component({ template: `<comp [dir]="val" [val]="val"></comp>`, standalone: false, }) class App { val = 'a'; } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val: new SimpleChange(undefined, 'a', true), }, }, { name: 'dir', changes: { dir: new SimpleChange(undefined, 'a', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'b'; fixture.detectChanges(); expect(events).toEqual([ { name: 'comp', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'dir', changes: { dir: new SimpleChange('a', 'b', false), }, }, ]); });
{ "end_byte": 14719, "start_byte": 7561, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_14723_21399
it('should be called on directives before component if component injects directives', () => { const events: any[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input() dir = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'dir', changes}); } } @Component({ selector: 'comp', template: `<p>{{val}}</p>`, standalone: false, }) class Comp { @Input() val = ''; constructor(public dir: Dir) {} ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp', changes}); } } @Component({ template: `<comp [dir]="val" [val]="val"></comp>`, standalone: false, }) class App { val = 'a'; } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'dir', changes: { dir: new SimpleChange(undefined, 'a', true), }, }, { name: 'comp', changes: { val: new SimpleChange(undefined, 'a', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'b'; fixture.detectChanges(); expect(events).toEqual([ { name: 'dir', changes: { dir: new SimpleChange('a', 'b', false), }, }, { name: 'comp', changes: { val: new SimpleChange('a', 'b', false), }, }, ]); }); it('should be called on multiple directives in injection order', () => { const events: any[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input() dir = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'dir', changes}); } } @Directive({ selector: '[injectionDir]', standalone: false, }) class InjectionDir { @Input() injectionDir = ''; constructor(public dir: Dir) {} ngOnChanges(changes: SimpleChanges) { events.push({name: 'injectionDir', changes}); } } @Component({ template: `<div [injectionDir]="val" [dir]="val"></div>`, standalone: false, }) class App { val = 'a'; } TestBed.configureTestingModule({ declarations: [App, InjectionDir, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'dir', changes: { dir: new SimpleChange(undefined, 'a', true), }, }, { name: 'injectionDir', changes: { injectionDir: new SimpleChange(undefined, 'a', true), }, }, ]); }); it('should be called on directives on an element', () => { const events: any[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input() dir = ''; @Input('dir-val') val = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'dir', changes}); } } @Component({ template: `<div [dir]="val1" [dir-val]="val2"></div>`, standalone: false, }) class App { val1 = 'a'; val2 = 'b'; } TestBed.configureTestingModule({ declarations: [App, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'dir', changes: { dir: new SimpleChange(undefined, 'a', true), val: new SimpleChange(undefined, 'b', true), }, }, ]); events.length = 0; fixture.componentInstance.val1 = 'a1'; fixture.componentInstance.val2 = 'b1'; fixture.detectChanges(); expect(events).toEqual([ { name: 'dir', changes: { dir: new SimpleChange('a', 'a1', false), val: new SimpleChange('b', 'b1', false), }, }, ]); }); it('should call onChanges properly in for loop', () => { const events: any[] = []; @Component({ selector: 'comp', template: `<p>{{val}}</p>`, standalone: false, }) class Comp { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'comp ' + this.name, changes}); } } @Component({ template: ` <comp name="0" [val]="val"></comp> <comp *ngFor="let number of numbers" [name]="number" [val]="val"></comp> <comp name="1" [val]="val"></comp> `, standalone: false, }) class App { val = 'a'; numbers = ['2', '3', '4']; } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'comp 0', changes: { name: new SimpleChange(undefined, '0', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'comp 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'comp 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'comp 3', changes: { name: new SimpleChange(undefined, '3', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'comp 4', changes: { name: new SimpleChange(undefined, '4', true), val: new SimpleChange(undefined, 'a', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'b'; fixture.detectChanges(); expect(events).toEqual([ { name: 'comp 0', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'comp 1', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'comp 2', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'comp 3', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'comp 4', changes: { val: new SimpleChange('a', 'b', false), }, }, ]); });
{ "end_byte": 21399, "start_byte": 14723, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_21403_26610
it('should call onChanges properly in for loop with children', () => { const events: any[] = []; @Component({ selector: 'child', template: `<p>{{val}}</p>`, standalone: false, }) class Child { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'child of parent ' + this.name, changes}); } } @Component({ selector: 'parent', template: `<child [name]="name" [val]="val"></child>`, standalone: false, }) class Parent { @Input() val = ''; @Input() name = ''; ngOnChanges(changes: SimpleChanges) { events.push({name: 'parent ' + this.name, changes}); } } @Component({ template: ` <parent name="0" [val]="val"></parent> <parent *ngFor="let number of numbers" [name]="number" [val]="val"></parent> <parent name="1" [val]="val"></parent> `, standalone: false, }) class App { val = 'a'; numbers = ['2', '3', '4']; } TestBed.configureTestingModule({ declarations: [App, Child, Parent], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ { name: 'parent 0', changes: { name: new SimpleChange(undefined, '0', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'parent 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'parent 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 2', changes: { name: new SimpleChange(undefined, '2', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'parent 3', changes: { name: new SimpleChange(undefined, '3', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 3', changes: { name: new SimpleChange(undefined, '3', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'parent 4', changes: { name: new SimpleChange(undefined, '4', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 4', changes: { name: new SimpleChange(undefined, '4', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 0', changes: { name: new SimpleChange(undefined, '0', true), val: new SimpleChange(undefined, 'a', true), }, }, { name: 'child of parent 1', changes: { name: new SimpleChange(undefined, '1', true), val: new SimpleChange(undefined, 'a', true), }, }, ]); events.length = 0; fixture.componentInstance.val = 'b'; fixture.detectChanges(); expect(events).toEqual([ { name: 'parent 0', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'parent 1', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'parent 2', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 2', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'parent 3', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 3', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'parent 4', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 4', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 0', changes: { val: new SimpleChange('a', 'b', false), }, }, { name: 'child of parent 1', changes: { val: new SimpleChange('a', 'b', false), }, }, ]); }); it('should not call onChanges if props are set directly', () => { const events: any[] = []; @Component({ template: `<p>{{value}}</p>`, standalone: false, }) class App { value = 'a'; ngOnChanges(changes: SimpleChanges) { events.push(changes); } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.value = 'b'; fixture.detectChanges(); expect(events).toEqual([]); }); });
{ "end_byte": 26610, "start_byte": 21403, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_26612_33783
describe('meta-programming', () => { it('should allow adding lifecycle hook methods any time before first instance creation', () => { const events: any[] = []; @Component({ template: `<child name="value"></child>`, standalone: false, }) class App {} @Component({ selector: 'child', template: `empty`, standalone: false, }) class Child { @Input() name: string = ''; } const ChildPrototype = Child.prototype as any; ChildPrototype.ngOnInit = () => events.push('onInit'); ChildPrototype.ngOnChanges = (e: SimpleChanges) => { const name = e['name']; expect(name.previousValue).toEqual(undefined); expect(name.currentValue).toEqual('value'); expect(name.firstChange).toEqual(true); events.push('ngOnChanges'); }; ChildPrototype.ngDoCheck = () => events.push('ngDoCheck'); ChildPrototype.ngAfterContentInit = () => events.push('ngAfterContentInit'); ChildPrototype.ngAfterContentChecked = () => events.push('ngAfterContentChecked'); ChildPrototype.ngAfterViewInit = () => events.push('ngAfterViewInit'); ChildPrototype.ngAfterViewChecked = () => events.push('ngAfterViewChecked'); ChildPrototype.ngOnDestroy = () => events.push('ngOnDestroy'); TestBed.configureTestingModule({ declarations: [App, Child], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(events).toEqual([ 'ngOnChanges', 'onInit', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked', 'ngAfterViewInit', 'ngAfterViewChecked', 'ngOnDestroy', ]); }); it('should allow adding lifecycle hook methods with inheritance any time before first instance creation', () => { const events: any[] = []; @Component({ template: `<child name="value"></child>`, standalone: false, }) class App {} class BaseChild {} @Component({ selector: 'child', template: `empty`, standalone: false, }) class Child extends BaseChild { @Input() name: string = ''; } // These are defined on the base class const BasePrototype = BaseChild.prototype as any; BasePrototype.ngOnInit = () => events.push('onInit'); BasePrototype.ngOnChanges = (e: SimpleChanges) => { const name = e['name']; expect(name.previousValue).toEqual(undefined); expect(name.currentValue).toEqual('value'); expect(name.firstChange).toEqual(true); events.push('ngOnChanges'); }; // These will be overwritten later BasePrototype.ngDoCheck = () => events.push('Expected to be overbidden'); BasePrototype.ngAfterContentInit = () => events.push('Expected to be overbidden'); // These are define on the concrete class const ChildPrototype = Child.prototype as any; ChildPrototype.ngDoCheck = () => events.push('ngDoCheck'); ChildPrototype.ngAfterContentInit = () => events.push('ngAfterContentInit'); ChildPrototype.ngAfterContentChecked = () => events.push('ngAfterContentChecked'); ChildPrototype.ngAfterViewInit = () => events.push('ngAfterViewInit'); ChildPrototype.ngAfterViewChecked = () => events.push('ngAfterViewChecked'); ChildPrototype.ngOnDestroy = () => events.push('ngOnDestroy'); TestBed.configureTestingModule({ declarations: [App, Child], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(events).toEqual([ 'ngOnChanges', 'onInit', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked', 'ngAfterViewInit', 'ngAfterViewChecked', 'ngOnDestroy', ]); }); }); it('should call all hooks in correct order when several directives on same node', () => { let log: string[] = []; class AllHooks { id: number = -1; /** @internal */ private _log(hook: string, id: number) { log.push(hook + id); } ngOnChanges() { this._log('onChanges', this.id); } ngOnInit() { this._log('onInit', this.id); } ngDoCheck() { this._log('doCheck', this.id); } ngAfterContentInit() { this._log('afterContentInit', this.id); } ngAfterContentChecked() { this._log('afterContentChecked', this.id); } ngAfterViewInit() { this._log('afterViewInit', this.id); } ngAfterViewChecked() { this._log('afterViewChecked', this.id); } } @Directive({ selector: 'div', standalone: false, }) class DirA extends AllHooks { @Input('a') override id: number = 0; } @Directive({ selector: 'div', standalone: false, }) class DirB extends AllHooks { @Input('b') override id: number = 0; } @Directive({ selector: 'div', standalone: false, }) class DirC extends AllHooks { @Input('c') override id: number = 0; } @Component({ selector: 'app-comp', template: '<div [a]="1" [b]="2" [c]="3"></div>', standalone: false, }) class AppComp {} TestBed.configureTestingModule({declarations: [AppComp, DirA, DirB, DirC]}); const fixture = TestBed.createComponent(AppComp); fixture.detectChanges(); expect(log).toEqual([ 'onChanges1', 'onInit1', 'doCheck1', 'onChanges2', 'onInit2', 'doCheck2', 'onChanges3', 'onInit3', 'doCheck3', 'afterContentInit1', 'afterContentChecked1', 'afterContentInit2', 'afterContentChecked2', 'afterContentInit3', 'afterContentChecked3', 'afterViewInit1', 'afterViewChecked1', 'afterViewInit2', 'afterViewChecked2', 'afterViewInit3', 'afterViewChecked3', ]); }); it('should call hooks after setting directives inputs', () => { let log: string[] = []; @Directive({ selector: 'div', standalone: false, }) class DirA { @Input() a: number = 0; ngOnInit() { log.push('onInitA' + this.a); } } @Directive({ selector: 'div', standalone: false, }) class DirB { @Input() b: number = 0; ngOnInit() { log.push('onInitB' + this.b); } ngDoCheck() { log.push('doCheckB' + this.b); } } @Directive({ selector: 'div', standalone: false, }) class DirC { @Input() c: number = 0; ngOnInit() { log.push('onInitC' + this.c); } ngDoCheck() { log.push('doCheckC' + this.c); } } @Component({ selector: 'app-comp', template: '<div [a]="id" [b]="id" [c]="id"></div><div [a]="id" [b]="id" [c]="id"></div>', standalone: false, }) class AppComp { id = 0; } TestBed.configureTestingModule({declarations: [AppComp, DirA, DirB, DirC]}); const fixture = TestBed.createComponent(AppComp); fixture.detectChanges(); expect(log).toEqual([ 'onInitA0', 'onInitB0', 'doCheckB0', 'onInitC0', 'doCheckC0', 'onInitA0', 'onInitB0', 'doCheckB0', 'onInitC0', 'doCheckC0', ]); log = []; fixture.componentInstance.id = 1; fixture.detectChanges(); expect(log).toEqual(['doCheckB1', 'doCheckC1', 'doCheckB1', 'doCheckC1']); });
{ "end_byte": 33783, "start_byte": 26612, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_33785_41445
describe('onInit', () => { it('should call onInit after inputs are the first time', () => { const input1Values: string[] = []; const input2Values: string[] = []; @Component({ selector: 'my-comp', template: `<p>test</p>`, standalone: false, }) class MyComponent { @Input() input1 = ''; @Input() input2 = ''; ngOnInit() { input1Values.push(this.input1); input2Values.push(this.input2); } } @Component({ template: ` <my-comp [input1]="value1" [input2]="value2"></my-comp> `, standalone: false, }) class App { value1 = 'a'; value2 = 'b'; } TestBed.configureTestingModule({ declarations: [App, MyComponent], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(input1Values).toEqual(['a']); expect(input2Values).toEqual(['b']); fixture.componentInstance.value1 = 'c'; fixture.componentInstance.value2 = 'd'; fixture.detectChanges(); // Shouldn't be called again just because change detection ran. expect(input1Values).toEqual(['a']); expect(input2Values).toEqual(['b']); }); it('should be called on root component', () => { let onInitCalled = 0; @Component({ template: ``, standalone: false, }) class App { ngOnInit() { onInitCalled++; } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(onInitCalled).toBe(1); }); it('should call parent onInit before it calls child onInit', () => { const initCalls: string[] = []; @Component({ selector: `child-comp`, template: `<p>child</p>`, standalone: false, }) class ChildComp { ngOnInit() { initCalls.push('child'); } } @Component({ template: `<child-comp></child-comp>`, standalone: false, }) class ParentComp { ngOnInit() { initCalls.push('parent'); } } TestBed.configureTestingModule({ declarations: [ParentComp, ChildComp], }); const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); expect(initCalls).toEqual(['parent', 'child']); }); it('should call all parent onInits across view before calling children onInits', () => { const initCalls: string[] = []; @Component({ selector: `child-comp`, template: `<p>child</p>`, standalone: false, }) class ChildComp { @Input() name = ''; ngOnInit() { initCalls.push(`child of parent ${this.name}`); } } @Component({ selector: 'parent-comp', template: `<child-comp [name]="name"></child-comp>`, standalone: false, }) class ParentComp { @Input() name = ''; ngOnInit() { initCalls.push(`parent ${this.name}`); } } @Component({ template: ` <parent-comp name="1"></parent-comp> <parent-comp name="2"></parent-comp> `, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, ParentComp, ChildComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(initCalls).toEqual(['parent 1', 'parent 2', 'child of parent 1', 'child of parent 2']); }); it('should call onInit every time a new view is created (if block)', () => { let onInitCalls = 0; @Component({ selector: 'my-comp', template: '<p>test</p>', standalone: false, }) class MyComp { ngOnInit() { onInitCalls++; } } @Component({ template: ` <div *ngIf="show"><my-comp></my-comp></div> `, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, MyComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(onInitCalls).toBe(1); fixture.componentInstance.show = false; fixture.detectChanges(); expect(onInitCalls).toBe(1); fixture.componentInstance.show = true; fixture.detectChanges(); expect(onInitCalls).toBe(2); }); it('should call onInit for children of dynamically created components', () => { @Component({ selector: 'my-comp', template: '<p>test</p>', standalone: false, }) class MyComp { onInitCalled = false; ngOnInit() { this.onInitCalled = true; } } @Component({ selector: 'dynamic-comp', template: ` <my-comp></my-comp> `, standalone: false, }) class DynamicComp {} @Component({ template: ` <div #container></div> `, standalone: false, }) class App { @ViewChild('container', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef; createDynamicView() { this.viewContainerRef.createComponent(DynamicComp); } } TestBed.configureTestingModule({declarations: [App, MyComp, DynamicComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.createDynamicView(); fixture.detectChanges(); const myComp = fixture.debugElement.query(By.directive(MyComp)).componentInstance; expect(myComp.onInitCalled).toBe(true); }); it('should call onInit in hosts before their content children', () => { const initialized: string[] = []; @Component({ selector: 'projected', template: '', standalone: false, }) class Projected { ngOnInit() { initialized.push('projected'); } } @Component({ selector: 'comp', template: `<ng-content></ng-content>`, standalone: false, }) class Comp { ngOnInit() { initialized.push('comp'); } } @Component({ template: ` <comp> <projected></projected> </comp> `, standalone: false, }) class App { ngOnInit() { initialized.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Projected], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(initialized).toEqual(['app', 'comp', 'projected']); }); it('should call onInit in host and its content children before next host', () => { const initialized: string[] = []; @Component({ selector: 'projected', template: '', standalone: false, }) class Projected { @Input() name = ''; ngOnInit() { initialized.push('projected ' + this.name); } } @Component({ selector: 'comp', template: `<ng-content></ng-content>`, standalone: false, }) class Comp { @Input() name = ''; ngOnInit() { initialized.push('comp ' + this.name); } } @Component({ template: ` <comp name="1"> <projected name="1"></projected> </comp> <comp name="2"> <projected name="2"></projected> </comp> `, standalone: false, }) class App { ngOnInit() { initialized.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Projected], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(initialized).toEqual(['app', 'comp 1', 'projected 1', 'comp 2', 'projected 2']); });
{ "end_byte": 41445, "start_byte": 33785, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_41449_47876
it('should be called on directives after component by default', () => { const initialized: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir-name') name = ''; ngOnInit() { initialized.push('dir ' + this.name); } } @Component({ selector: 'comp', template: `<p></p>`, standalone: false, }) class Comp { @Input() name = ''; ngOnInit() { initialized.push('comp ' + this.name); } } @Component({ template: ` <comp name="1" dir dir-name="1"></comp> <comp name="2" dir dir-name="2"></comp> `, standalone: false, }) class App { ngOnInit() { initialized.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(initialized).toEqual(['app', 'comp 1', 'dir 1', 'comp 2', 'dir 2']); }); it('should be called on multiple directives in injection order', () => { const events: any[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input() dir = ''; ngOnInit() { events.push('dir'); } } @Directive({ selector: '[injectionDir]', standalone: false, }) class InjectionDir { @Input() injectionDir = ''; constructor(public dir: Dir) {} ngOnInit() { events.push('injectionDir'); } } @Component({ template: `<div [injectionDir]="val" [dir]="val"></div>`, standalone: false, }) class App { val = 'a'; ngOnInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, InjectionDir, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['app', 'dir', 'injectionDir']); }); it('should be called on directives before component if component injects directives', () => { const initialized: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir-name') name = ''; ngOnInit() { initialized.push('dir ' + this.name); } } @Component({ selector: 'comp', template: `<p></p>`, standalone: false, }) class Comp { @Input() name = ''; constructor(public dir: Dir) {} ngOnInit() { initialized.push('comp ' + this.name); } } @Component({ template: ` <comp name="1" dir dir-name="1"></comp> <comp name="2" dir dir-name="2"></comp> `, standalone: false, }) class App { ngOnInit() { initialized.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(initialized).toEqual(['app', 'dir 1', 'comp 1', 'dir 2', 'comp 2']); }); it('should be called on directives on an element', () => { const initialized: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir-name') name = ''; ngOnInit() { initialized.push('dir ' + this.name); } } @Component({ template: ` <p name="1" dir dir-name="1"></p> <p name="2" dir dir-name="2"></p> `, standalone: false, }) class App { ngOnInit() { initialized.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(initialized).toEqual(['app', 'dir 1', 'dir 2']); }); it('should call onInit properly in for loop', () => { const initialized: string[] = []; @Component({ selector: 'comp', template: `<p></p>`, standalone: false, }) class Comp { @Input() name = ''; ngOnInit() { initialized.push('comp ' + this.name); } } @Component({ template: ` <comp name="0"></comp> <comp *ngFor="let number of numbers" [name]="number"></comp> <comp name="1"></comp> `, standalone: false, }) class App { numbers = [2, 3, 4, 5, 6]; } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(initialized).toEqual([ 'comp 0', 'comp 1', 'comp 2', 'comp 3', 'comp 4', 'comp 5', 'comp 6', ]); }); it('should call onInit properly in for loop with children', () => { const initialized: string[] = []; @Component({ selector: 'child', template: `<p></p>`, standalone: false, }) class Child { @Input() name = ''; ngOnInit() { initialized.push('child of parent ' + this.name); } } @Component({ selector: 'parent', template: '<child [name]="name"></child>', standalone: false, }) class Parent { @Input() name = ''; ngOnInit() { initialized.push('parent ' + this.name); } } @Component({ template: ` <parent name="0"></parent> <parent *ngFor="let number of numbers" [name]="number"></parent> <parent name="1"></parent> `, standalone: false, }) class App { numbers = [2, 3, 4, 5, 6]; } TestBed.configureTestingModule({ declarations: [App, Child, Parent], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(initialized).toEqual([ // First the two root level components 'parent 0', 'parent 1', // Then our 5 embedded views 'parent 2', 'child of parent 2', 'parent 3', 'child of parent 3', 'parent 4', 'child of parent 4', 'parent 5', 'child of parent 5', 'parent 6', 'child of parent 6', // Then the children of the root level components 'child of parent 0', 'child of parent 1', ]); }); });
{ "end_byte": 47876, "start_byte": 41449, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_47878_53589
describe('doCheck', () => { it('should call doCheck on every refresh', () => { let doCheckCalled = 0; @Component({ template: ``, standalone: false, }) class App { ngDoCheck() { doCheckCalled++; } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(doCheckCalled).toBe(1); fixture.detectChanges(); expect(doCheckCalled).toBe(2); }); it('should call parent doCheck before child doCheck', () => { const doChecks: string[] = []; @Component({ selector: 'parent', template: `<child></child>`, standalone: false, }) class Parent { ngDoCheck() { doChecks.push('parent'); } } @Component({ selector: 'child', template: ``, standalone: false, }) class Child { ngDoCheck() { doChecks.push('child'); } } @Component({ template: `<parent></parent>`, standalone: false, }) class App { ngDoCheck() { doChecks.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Parent, Child], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(doChecks).toEqual(['app', 'parent', 'child']); }); it('should call ngOnInit before ngDoCheck if creation mode', () => { const events: string[] = []; @Component({ template: ``, standalone: false, }) class App { ngOnInit() { events.push('onInit'); } ngDoCheck() { events.push('doCheck'); } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['onInit', 'doCheck']); }); it('should be called on directives after component by default', () => { const doChecks: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngDoCheck() { doChecks.push('dir ' + this.name); } } @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngDoCheck() { doChecks.push('comp ' + this.name); } } @Component({ template: ` <comp name="1" dir="1"></comp> <comp name="2" dir="2"></comp> `, standalone: false, }) class App { ngDoCheck() { doChecks.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(doChecks).toEqual(['app', 'comp 1', 'dir 1', 'comp 2', 'dir 2']); }); it('should be called on directives before component if component injects directives', () => { const doChecks: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngDoCheck() { doChecks.push('dir ' + this.name); } } @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; constructor(public dir: Dir) {} ngDoCheck() { doChecks.push('comp ' + this.name); } } @Component({ template: ` <comp name="1" dir="1"></comp> <comp name="2" dir="2"></comp> `, standalone: false, }) class App { ngDoCheck() { doChecks.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(doChecks).toEqual(['app', 'dir 1', 'comp 1', 'dir 2', 'comp 2']); }); it('should be called on multiple directives in injection order', () => { const events: any[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input() dir = ''; ngDoCheck() { events.push('dir'); } } @Directive({ selector: '[injectionDir]', standalone: false, }) class InjectionDir { @Input() injectionDir = ''; constructor(public dir: Dir) {} ngDoCheck() { events.push('injectionDir'); } } @Component({ template: `<div [injectionDir]="val" [dir]="val"></div>`, standalone: false, }) class App { val = 'a'; ngDoCheck() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, InjectionDir, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['app', 'dir', 'injectionDir']); }); it('should be called on directives on an element', () => { const doChecks: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngDoCheck() { doChecks.push('dir ' + this.name); } } @Component({ template: ` <p dir="1"></p> <p dir="2"></p> `, standalone: false, }) class App { ngDoCheck() { doChecks.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(doChecks).toEqual(['app', 'dir 1', 'dir 2']); }); });
{ "end_byte": 53589, "start_byte": 47878, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_53591_61589
describe('afterContentinit', () => { it('should be called only in creation mode', () => { let afterContentInitCalls = 0; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { ngAfterContentInit() { afterContentInitCalls++; } } @Component({ template: `<comp></comp>`, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // two updates fixture.detectChanges(); fixture.detectChanges(); expect(afterContentInitCalls).toBe(1); }); it('should be called on root component in creation mode', () => { let afterContentInitCalls = 0; @Component({ template: `<p>test</p>`, standalone: false, }) class App { ngAfterContentInit() { afterContentInitCalls++; } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // two updates fixture.detectChanges(); fixture.detectChanges(); expect(afterContentInitCalls).toBe(1); }); it('should be called on every create ngIf', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { ngAfterContentInit() { events.push('comp afterContentInit'); } } @Component({ template: `<comp *ngIf="show"></comp>`, standalone: false, }) class App { show = true; ngAfterContentInit() { events.push('app afterContentInit'); } } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['app afterContentInit', 'comp afterContentInit']); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['app afterContentInit', 'comp afterContentInit']); fixture.componentInstance.show = true; fixture.detectChanges(); expect(events).toEqual([ 'app afterContentInit', 'comp afterContentInit', 'comp afterContentInit', ]); }); it('should be called in parents before children', () => { const events: string[] = []; @Component({ selector: 'parent', template: `<child [name]="name"></child>`, standalone: false, }) class Parent { @Input() name = ''; ngAfterContentInit() { events.push('parent ' + this.name); } } @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() name = ''; ngAfterContentInit() { events.push('child of parent ' + this.name); } } @Component({ template: ` <parent name="1"></parent> <parent name="2"></parent> `, standalone: false, }) class App { ngAfterContentInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Parent, Child], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'app', 'parent 1', 'parent 2', 'child of parent 1', 'child of parent 2', ]); }); it('should be called in projected components before their hosts', () => { const events: string[] = []; @Component({ selector: 'projected-child', template: `<p>test</p>`, standalone: false, }) class ProjectedChild { @Input() name = ''; ngAfterContentInit() { events.push('projected child ' + this.name); } } @Component({ selector: 'comp', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Comp { @Input() name = ''; ngAfterContentInit() { events.push('comp ' + this.name); } } @Component({ selector: 'projected', template: `<projected-child [name]=name></projected-child>`, standalone: false, }) class Projected { @Input() name = ''; ngAfterContentInit() { events.push('projected ' + this.name); } } @Component({ template: ` <comp name="1"> <projected name="1"></projected> <projected name="2"></projected> </comp> <comp name="2"> <projected name="3"></projected> <projected name="4"></projected> </comp> `, standalone: false, }) class App { ngAfterContentInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Projected, ProjectedChild], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ // root 'app', // projections of comp 1 'projected 1', 'projected 2', // comp 1 'comp 1', // projections of comp 2 'projected 3', 'projected 4', // comp 2 'comp 2', // children of projections 'projected child 1', 'projected child 2', 'projected child 3', 'projected child 4', ]); }); it('should be called in correct order in a for loop', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngAfterContentInit() { events.push('comp ' + this.name); } } @Component({ template: ` <comp name="4"></comp> <comp *ngFor="let number of numbers" [name]="number"></comp> <comp name="5"></comp> `, standalone: false, }) class App { numbers = [0, 1, 2, 3]; ngAfterContentInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['app', 'comp 0', 'comp 1', 'comp 2', 'comp 3', 'comp 4', 'comp 5']); }); it('should be called in correct order in a for loop with children', () => { const events: string[] = []; @Component({ selector: 'parent', template: `<child [name]=name></child>`, standalone: false, }) class Parent { @Input() name = ''; ngAfterContentInit() { events.push('parent ' + this.name); } } @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() name = ''; ngAfterContentInit() { events.push('child of parent ' + this.name); } } @Component({ template: ` <parent name="4"></parent> <parent *ngFor="let number of numbers" [name]="number"></parent> <parent name="5"></parent> `, standalone: false, }) class App { numbers = [0, 1, 2, 3]; ngAfterContentInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Parent, Child], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ // root 'app', // 4 embedded views 'parent 0', 'child of parent 0', 'parent 1', 'child of parent 1', 'parent 2', 'child of parent 2', 'parent 3', 'child of parent 3', // root children 'parent 4', 'parent 5', // children of root children 'child of parent 4', 'child of parent 5', ]); });
{ "end_byte": 61589, "start_byte": 53591, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_61593_63685
it('should be called on directives after component', () => { const events: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngAfterContentInit() { events.push('dir ' + this.name); } } @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngAfterContentInit() { events.push('comp ' + this.name); } } @Component({ template: ` <comp name="1" dir="1"></comp> <comp name="2" dir="2"></comp> `, standalone: false, }) class App { ngAfterContentInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['app', 'comp 1', 'dir 1', 'comp 2', 'dir 2']); }); }); describe('afterContentChecked', () => { it('should be called every change detection run after afterContentInit', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { ngAfterContentInit() { events.push('comp afterContentInit'); } ngAfterContentChecked() { events.push('comp afterContentChecked'); } } @Component({ template: `<comp></comp>`, standalone: false, }) class App { ngAfterContentInit() { events.push('app afterContentInit'); } ngAfterContentChecked() { events.push('app afterContentChecked'); } } TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'app afterContentInit', 'app afterContentChecked', 'comp afterContentInit', 'comp afterContentChecked', ]); }); });
{ "end_byte": 63685, "start_byte": 61593, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_63687_70718
describe('afterViewInit', () => { it('should be called on creation and not in update mode', () => { let afterViewInitCalls = 0; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { ngAfterViewInit() { afterViewInitCalls++; } } @Component({ template: `<comp></comp>`, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // two updates fixture.detectChanges(); fixture.detectChanges(); expect(afterViewInitCalls).toBe(1); }); it('should be called on root component in creation mode', () => { let afterViewInitCalls = 0; @Component({ template: `<p>test</p>`, standalone: false, }) class App { ngAfterViewInit() { afterViewInitCalls++; } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // two updates fixture.detectChanges(); fixture.detectChanges(); expect(afterViewInitCalls).toBe(1); }); it('should be called every time a view is initialized with ngIf', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { ngAfterViewInit() { events.push('comp'); } } @Component({ template: `<comp *ngIf="show"></comp>`, standalone: false, }) class App { show = true; ngAfterViewInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['comp', 'app']); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['comp', 'app']); fixture.componentInstance.show = true; fixture.detectChanges(); expect(events).toEqual(['comp', 'app', 'comp']); }); it('should be called in children before parents', () => { const events: string[] = []; @Component({ selector: 'parent', template: `<child [name]=name></child>`, standalone: false, }) class Parent { @Input() name = ''; ngAfterViewInit() { events.push('parent ' + this.name); } } @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() name = ''; ngAfterViewInit() { events.push('child of parent ' + this.name); } } @Component({ template: ` <parent name="1"></parent> <parent name="2"></parent> `, standalone: false, }) class App { ngAfterViewInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Parent, Child], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'child of parent 1', 'child of parent 2', 'parent 1', 'parent 2', 'app', ]); }); it('should be called in projected components before their hosts', () => { const events: string[] = []; @Component({ selector: 'projected', template: `<p>test</p>`, standalone: false, }) class Projected { @Input() name = ''; ngAfterViewInit() { events.push('projected ' + this.name); } } @Component({ selector: 'comp', template: `<ng-content></ng-content>`, standalone: false, }) class Comp { @Input() name = ''; ngAfterViewInit() { events.push('comp ' + this.name); } } @Component({ template: ` <comp name="1"><projected name="1"></projected></comp> <comp name="2"><projected name="2"></projected></comp> `, standalone: false, }) class App { ngAfterViewInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Projected], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['projected 1', 'comp 1', 'projected 2', 'comp 2', 'app']); }); it('should call afterViewInit in content children and host before next host', () => { const events: string[] = []; @Component({ selector: 'projected-child', template: `<p>test</p>`, standalone: false, }) class ProjectedChild { @Input() name = ''; ngAfterViewInit() { events.push('child of projected ' + this.name); } } @Component({ selector: 'projected', template: `<projected-child [name]="name"></projected-child>`, standalone: false, }) class Projected { @Input() name = ''; ngAfterViewInit() { events.push('projected ' + this.name); } } @Component({ selector: 'comp', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Comp { @Input() name = ''; ngAfterViewInit() { events.push('comp ' + this.name); } } @Component({ template: ` <comp name="1"><projected name="1"></projected></comp> <comp name="2"><projected name="2"></projected></comp> `, standalone: false, }) class App { ngAfterViewInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Projected, ProjectedChild], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'child of projected 1', 'child of projected 2', 'projected 1', 'comp 1', 'projected 2', 'comp 2', 'app', ]); }); it('should be called in correct order with ngFor', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngAfterViewInit() { events.push('comp ' + this.name); } } @Component({ template: ` <comp name="4"></comp> <comp *ngFor="let number of numbers" [name]="number"></comp> <comp name="5"></comp> `, standalone: false, }) class App { numbers = [0, 1, 2, 3]; ngAfterViewInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['comp 0', 'comp 1', 'comp 2', 'comp 3', 'comp 4', 'comp 5', 'app']); });
{ "end_byte": 70718, "start_byte": 63687, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_70722_73944
it('should be called in correct order with for loops with children', () => { const events: string[] = []; @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() name = ''; ngAfterViewInit() { events.push('child of parent ' + this.name); } } @Component({ selector: 'parent', template: `<child [name]="name"></child>`, standalone: false, }) class Parent { @Input() name = ''; ngAfterViewInit() { events.push('parent ' + this.name); } } @Component({ template: ` <parent name="4"></parent> <parent *ngFor="let number of numbers" [name]="number"></parent> <parent name="5"></parent> `, standalone: false, }) class App { numbers = [0, 1, 2, 3]; ngAfterViewInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Parent, Child], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'child of parent 0', 'parent 0', 'child of parent 1', 'parent 1', 'child of parent 2', 'parent 2', 'child of parent 3', 'parent 3', 'child of parent 4', 'child of parent 5', 'parent 4', 'parent 5', 'app', ]); }); it('should be called on directives after component', () => { const events: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngAfterViewInit() { events.push('dir ' + this.name); } } @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngAfterViewInit() { events.push('comp ' + this.name); } } @Component({ template: ` <comp name="1" dir="1"></comp> <comp name="2" dir="2"></comp> `, standalone: false, }) class App { ngAfterViewInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['comp 1', 'dir 1', 'comp 2', 'dir 2', 'app']); }); it('should be called on directives on an element', () => { const events: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngAfterViewInit() { events.push('dir ' + this.name); } } @Component({ template: ` <div dir="1"></div> <div dir="2"></div> `, standalone: false, }) class App { ngAfterViewInit() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['dir 1', 'dir 2', 'app']); }); });
{ "end_byte": 73944, "start_byte": 70722, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_73946_79328
describe('afterViewChecked', () => { it('should call ngAfterViewChecked every update', () => { let afterViewCheckedCalls = 0; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { ngAfterViewChecked() { afterViewCheckedCalls++; } } @Component({ template: `<comp></comp>`, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(afterViewCheckedCalls).toBe(1); fixture.detectChanges(); expect(afterViewCheckedCalls).toBe(2); fixture.detectChanges(); expect(afterViewCheckedCalls).toBe(3); }); it('should be called on root component', () => { let afterViewCheckedCalls = 0; @Component({ template: `<p>test</p>`, standalone: false, }) class App { ngAfterViewChecked() { afterViewCheckedCalls++; } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(afterViewCheckedCalls).toBe(1); fixture.detectChanges(); expect(afterViewCheckedCalls).toBe(2); fixture.detectChanges(); expect(afterViewCheckedCalls).toBe(3); }); it('should call ngAfterViewChecked with bindings', () => { let afterViewCheckedCalls = 0; @Component({ selector: 'comp', template: `<p>{{value}}</p>`, standalone: false, }) class Comp { @Input() value = ''; ngAfterViewChecked() { afterViewCheckedCalls++; } } @Component({ template: `<comp [value]="value"></comp>`, standalone: false, }) class App { value = 1; } TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(afterViewCheckedCalls).toBe(1); fixture.componentInstance.value = 1337; fixture.detectChanges(); expect(afterViewCheckedCalls).toBe(2); }); it('should be called in correct order with for loops with children', () => { const events: string[] = []; @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() name = ''; ngAfterViewChecked() { events.push('child of parent ' + this.name); } } @Component({ selector: 'parent', template: `<child [name]="name"></child>`, standalone: false, }) class Parent { @Input() name = ''; ngAfterViewChecked() { events.push('parent ' + this.name); } } @Component({ template: ` <parent name="4"></parent> <parent *ngFor="let number of numbers" [name]="number"></parent> <parent name="5"></parent> `, standalone: false, }) class App { numbers = [0, 1, 2, 3]; ngAfterViewChecked() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Parent, Child], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'child of parent 0', 'parent 0', 'child of parent 1', 'parent 1', 'child of parent 2', 'parent 2', 'child of parent 3', 'parent 3', 'child of parent 4', 'child of parent 5', 'parent 4', 'parent 5', 'app', ]); }); it('should be called on directives after component', () => { const events: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngAfterViewChecked() { events.push('dir ' + this.name); } } @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngAfterViewChecked() { events.push('comp ' + this.name); } } @Component({ template: ` <comp name="1" dir="1"></comp> <comp name="2" dir="2"></comp> `, standalone: false, }) class App { ngAfterViewChecked() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Comp, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['comp 1', 'dir 1', 'comp 2', 'dir 2', 'app']); }); it('should be called on directives on an element', () => { const events: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngAfterViewChecked() { events.push('dir ' + this.name); } } @Component({ template: ` <div dir="1"></div> <div dir="2"></div> `, standalone: false, }) class App { ngAfterViewChecked() { events.push('app'); } } TestBed.configureTestingModule({ declarations: [App, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual(['dir 1', 'dir 2', 'app']); }); });
{ "end_byte": 79328, "start_byte": 73946, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_79330_86855
describe('onDestroy', () => { it('should call destroy when view is removed', () => { let destroyCalled = 0; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { ngOnDestroy() { destroyCalled++; } } @Component({ template: `<comp *ngIf="show"></comp>`, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(destroyCalled).toBe(0); fixture.componentInstance.show = false; fixture.detectChanges(); expect(destroyCalled).toBe(1); fixture.componentInstance.show = true; fixture.detectChanges(); expect(destroyCalled).toBe(1); fixture.componentInstance.show = false; fixture.detectChanges(); expect(destroyCalled).toBe(2); }); it('should call destroy when multiple views are removed', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngOnDestroy() { events.push('comp ' + this.name); } } @Component({ template: ` <div *ngIf="show"> <comp name="1"></comp> <comp name="2"></comp> </div> `, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['comp 1', 'comp 2']); }); it('should be called in child components before parent components', () => { const events: string[] = []; @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() name = ''; ngOnDestroy() { events.push('child of parent ' + this.name); } } @Component({ selector: 'parent', template: `<child [name]="name"></child>`, standalone: false, }) class Parent { @Input() name = ''; ngOnDestroy() { events.push('parent ' + this.name); } } @Component({ template: ` <div *ngIf="show"> <parent name="1"></parent> <parent name="2"></parent> </div> `, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, Parent, Child], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['child of parent 1', 'child of parent 2', 'parent 1', 'parent 2']); }); it('should be called bottom up with children nested 2 levels deep', () => { const events: string[] = []; @Component({ selector: 'child', template: `<p>test</p>`, standalone: false, }) class Child { @Input() name = ''; ngOnDestroy() { events.push('child ' + this.name); } } @Component({ selector: 'parent', template: `<child [name]="name"></child>`, standalone: false, }) class Parent { @Input() name = ''; ngOnDestroy() { events.push('parent ' + this.name); } } @Component({ selector: 'grandparent', template: `<parent [name]="name"></parent>`, standalone: false, }) class Grandparent { @Input() name = ''; ngOnDestroy() { events.push('grandparent ' + this.name); } } @Component({ template: ` <div *ngIf="show"> <grandparent name="1"></grandparent> <grandparent name="2"></grandparent> </div> `, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, Grandparent, Parent, Child], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual([ 'child 1', 'parent 1', 'child 2', 'parent 2', 'grandparent 1', 'grandparent 2', ]); }); it('should be called in projected components before their hosts', () => { const events: string[] = []; @Component({ selector: 'projected', template: `<p>test</p>`, standalone: false, }) class Projected { @Input() name = ''; ngOnDestroy() { events.push('projected ' + this.name); } } @Component({ selector: 'comp', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Comp { @Input() name = ''; ngOnDestroy() { events.push('comp ' + this.name); } } @Component({ template: ` <div *ngIf="show"> <comp name="1"> <projected name="1"></projected> </comp> <comp name="2"> <projected name="2"></projected> </comp> </div> `, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, Comp, Projected], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['projected 1', 'comp 1', 'projected 2', 'comp 2']); }); it('should be called in consistent order if views are removed and re-added', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngOnDestroy() { events.push('comp ' + this.name); } } @Component({ template: ` <div *ngIf="showAll"> <comp name="1"></comp> <comp *ngIf="showMiddle" name="2"></comp> <comp name="3"></comp> </div> `, standalone: false, }) class App { showAll = true; showMiddle = true; } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.showMiddle = false; fixture.detectChanges(); expect(events).toEqual(['comp 2']); fixture.componentInstance.showAll = false; fixture.detectChanges(); expect(events).toEqual(['comp 2', 'comp 1', 'comp 3']); fixture.componentInstance.showAll = true; fixture.componentInstance.showMiddle = true; fixture.detectChanges(); expect(events).toEqual(['comp 2', 'comp 1', 'comp 3']); fixture.componentInstance.showAll = false; fixture.detectChanges(); expect(events).toEqual(['comp 2', 'comp 1', 'comp 3', 'comp 2', 'comp 1', 'comp 3']); });
{ "end_byte": 86855, "start_byte": 79330, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_86859_93454
it('should be called on every iteration of a destroyed for loop', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngOnDestroy() { events.push('comp ' + this.name); } } @Component({ template: ` <div *ngIf="show"> <comp *ngFor="let number of numbers" [name]="number"></comp> </div> `, standalone: false, }) class App { show = true; numbers = [0, 1, 2, 3]; } TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['comp 0', 'comp 1', 'comp 2', 'comp 3']); fixture.componentInstance.show = true; fixture.detectChanges(); expect(events).toEqual(['comp 0', 'comp 1', 'comp 2', 'comp 3']); fixture.componentInstance.numbers.splice(1, 1); fixture.detectChanges(); expect(events).toEqual(['comp 0', 'comp 1', 'comp 2', 'comp 3', 'comp 1']); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual([ 'comp 0', 'comp 1', 'comp 2', 'comp 3', 'comp 1', 'comp 0', 'comp 2', 'comp 3', ]); }); it('should call destroy properly if view also has listeners', () => { const events: string[] = []; @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { ngOnDestroy() { events.push('comp'); } } @Component({ template: ` <div *ngIf="show"> <button (click)="handleClick1()">test 1</button> <comp></comp> <button (click)="handleClick2()">test 2</button> </div> `, standalone: false, }) class App { show = true; clicksToButton1 = 0; clicksToButton2 = 0; handleClick1() { this.clicksToButton1++; } handleClick2() { this.clicksToButton2++; } } TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const buttons = fixture.debugElement.queryAll(By.css('button')); buttons.forEach((button) => button.nativeElement.click()); expect(fixture.componentInstance.clicksToButton1).toBe(1); expect(fixture.componentInstance.clicksToButton2).toBe(1); expect(events).toEqual([]); fixture.componentInstance.show = false; fixture.detectChanges(); buttons.forEach((button) => button.nativeElement.click()); expect(fixture.componentInstance.clicksToButton1).toBe(1); expect(fixture.componentInstance.clicksToButton2).toBe(1); expect(events).toEqual(['comp']); }); it('should not produce errors if change detection is triggered during ngOnDestroy', () => { @Component({ selector: 'child', template: `<ng-content></ng-content>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<ng-content></ng-content>`, standalone: false, }) class Parent { @ContentChildren(Child, {descendants: true}) child!: QueryList<Child>; } @Component({ selector: 'app', template: ` <ng-template #tpl> <parent> <child></child> </parent> </ng-template> <div #container dir></div> `, standalone: false, }) class App { @ViewChild('container', {read: ViewContainerRef, static: true}) container!: ViewContainerRef; @ViewChild('tpl', {read: TemplateRef, static: true}) tpl!: TemplateRef<any>; ngOnInit() { this.container.createEmbeddedView(this.tpl); } } @Directive({ selector: '[dir]', standalone: false, }) class Dir { constructor(public cdr: ChangeDetectorRef) {} ngOnDestroy() { // Important: calling detectChanges in destroy hook like that // doesn’t have practical purpose, but in real-world cases it might // happen, for example as a result of "focus()" call on a DOM element, // in case ZoneJS is active. this.cdr.detectChanges(); } } TestBed.configureTestingModule({ declarations: [App, Parent, Child, Dir], }); const fixture = TestBed.createComponent(App); fixture.autoDetectChanges(); expect(() => fixture.destroy()).not.toThrow(); }); it('should be called on directives after component', () => { const events: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') name = ''; ngOnDestroy() { events.push('dir ' + this.name); } } @Component({ selector: 'comp', template: `<p>test</p>`, standalone: false, }) class Comp { @Input() name = ''; ngOnDestroy() { events.push('comp ' + this.name); } } @Component({ template: ` <div *ngIf="show"> <comp name="1" dir="1"></comp> <comp name="2" dir="2"></comp> </div> `, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, Dir, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['comp 1', 'dir 1', 'comp 2', 'dir 2']); }); it('should be called on directives on an element', () => { const events: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir { ngOnDestroy() { events.push('dir'); } } @Component({ template: `<p *ngIf="show" dir></p>`, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, Dir], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([]); fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['dir']); }); });
{ "end_byte": 93454, "start_byte": 86859, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_93456_101884
scribe('hook order', () => { let events: string[] = []; beforeEach(() => (events = [])); @Component({ selector: 'comp', template: `{{value}}<div><ng-content></ng-content></div>`, standalone: false, }) class Comp { @Input() value = ''; @Input() name = ''; ngOnInit() { events.push(`${this.name} onInit`); } ngDoCheck() { events.push(`${this.name} doCheck`); } ngOnChanges() { events.push(`${this.name} onChanges`); } ngAfterContentInit() { events.push(`${this.name} afterContentInit`); } ngAfterContentChecked() { events.push(`${this.name} afterContentChecked`); } ngAfterViewInit() { events.push(`${this.name} afterViewInit`); } ngAfterViewChecked() { events.push(`${this.name} afterViewChecked`); } ngOnDestroy() { events.push(`${this.name} onDestroy`); } } @Component({ selector: 'parent', template: `<comp [name]="'child of ' + this.name" [value]="value"><ng-content></ng-content></comp>`, standalone: false, }) class Parent extends Comp {} it('should call all hooks in correct order', () => { @Component({ template: `<comp *ngIf="show" name="comp" [value]="value"></comp>`, standalone: false, }) class App { value = 'a'; show = true; } TestBed.configureTestingModule({ declarations: [App, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'comp onChanges', 'comp onInit', 'comp doCheck', 'comp afterContentInit', 'comp afterContentChecked', 'comp afterViewInit', 'comp afterViewChecked', ]); events.length = 0; fixture.detectChanges(); expect(events).toEqual(['comp doCheck', 'comp afterContentChecked', 'comp afterViewChecked']); events.length = 0; fixture.componentInstance.value = 'b'; fixture.detectChanges(); expect(events).toEqual([ 'comp onChanges', 'comp doCheck', 'comp afterContentChecked', 'comp afterViewChecked', ]); events.length = 0; fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual(['comp onDestroy']); }); it('should call all hooks in correct order with children', () => { @Component({ template: ` <div *ngIf="show"> <parent name="parent1" [value]="value"></parent> <parent name="parent2" [value]="value"></parent> </div> `, standalone: false, }) class App { value = 'a'; show = true; } TestBed.configureTestingModule({ declarations: [App, Parent, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'parent1 onChanges', 'parent1 onInit', 'parent1 doCheck', 'parent2 onChanges', 'parent2 onInit', 'parent2 doCheck', 'parent1 afterContentInit', 'parent1 afterContentChecked', 'parent2 afterContentInit', 'parent2 afterContentChecked', 'child of parent1 onChanges', 'child of parent1 onInit', 'child of parent1 doCheck', 'child of parent1 afterContentInit', 'child of parent1 afterContentChecked', 'child of parent1 afterViewInit', 'child of parent1 afterViewChecked', 'child of parent2 onChanges', 'child of parent2 onInit', 'child of parent2 doCheck', 'child of parent2 afterContentInit', 'child of parent2 afterContentChecked', 'child of parent2 afterViewInit', 'child of parent2 afterViewChecked', 'parent1 afterViewInit', 'parent1 afterViewChecked', 'parent2 afterViewInit', 'parent2 afterViewChecked', ]); events.length = 0; fixture.componentInstance.value = 'b'; fixture.detectChanges(); expect(events).toEqual([ 'parent1 onChanges', 'parent1 doCheck', 'parent2 onChanges', 'parent2 doCheck', 'parent1 afterContentChecked', 'parent2 afterContentChecked', 'child of parent1 onChanges', 'child of parent1 doCheck', 'child of parent1 afterContentChecked', 'child of parent1 afterViewChecked', 'child of parent2 onChanges', 'child of parent2 doCheck', 'child of parent2 afterContentChecked', 'child of parent2 afterViewChecked', 'parent1 afterViewChecked', 'parent2 afterViewChecked', ]); events.length = 0; fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual([ 'child of parent1 onDestroy', 'child of parent2 onDestroy', 'parent1 onDestroy', 'parent2 onDestroy', ]); }); // Angular 5 reference: https://stackblitz.com/edit/lifecycle-hooks-ng it('should call all hooks in correct order with view and content', () => { @Component({ template: ` <div *ngIf="show"> <parent name="parent1" [value]="value"> <comp name="projected1" [value]="value"></comp> </parent> <parent name="parent2" [value]="value"> <comp name="projected2" [value]="value"></comp> </parent> </div> `, standalone: false, }) class App { value = 'a'; show = true; } TestBed.configureTestingModule({ declarations: [App, Parent, Comp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(events).toEqual([ 'parent1 onChanges', 'parent1 onInit', 'parent1 doCheck', 'projected1 onChanges', 'projected1 onInit', 'projected1 doCheck', 'parent2 onChanges', 'parent2 onInit', 'parent2 doCheck', 'projected2 onChanges', 'projected2 onInit', 'projected2 doCheck', 'projected1 afterContentInit', 'projected1 afterContentChecked', 'parent1 afterContentInit', 'parent1 afterContentChecked', 'projected2 afterContentInit', 'projected2 afterContentChecked', 'parent2 afterContentInit', 'parent2 afterContentChecked', 'child of parent1 onChanges', 'child of parent1 onInit', 'child of parent1 doCheck', 'child of parent1 afterContentInit', 'child of parent1 afterContentChecked', 'child of parent1 afterViewInit', 'child of parent1 afterViewChecked', 'child of parent2 onChanges', 'child of parent2 onInit', 'child of parent2 doCheck', 'child of parent2 afterContentInit', 'child of parent2 afterContentChecked', 'child of parent2 afterViewInit', 'child of parent2 afterViewChecked', 'projected1 afterViewInit', 'projected1 afterViewChecked', 'parent1 afterViewInit', 'parent1 afterViewChecked', 'projected2 afterViewInit', 'projected2 afterViewChecked', 'parent2 afterViewInit', 'parent2 afterViewChecked', ]); events.length = 0; fixture.componentInstance.value = 'b'; fixture.detectChanges(); expect(events).toEqual([ 'parent1 onChanges', 'parent1 doCheck', 'projected1 onChanges', 'projected1 doCheck', 'parent2 onChanges', 'parent2 doCheck', 'projected2 onChanges', 'projected2 doCheck', 'projected1 afterContentChecked', 'parent1 afterContentChecked', 'projected2 afterContentChecked', 'parent2 afterContentChecked', 'child of parent1 onChanges', 'child of parent1 doCheck', 'child of parent1 afterContentChecked', 'child of parent1 afterViewChecked', 'child of parent2 onChanges', 'child of parent2 doCheck', 'child of parent2 afterContentChecked', 'child of parent2 afterViewChecked', 'projected1 afterViewChecked', 'parent1 afterViewChecked', 'projected2 afterViewChecked', 'parent2 afterViewChecked', ]); events.length = 0; fixture.componentInstance.show = false; fixture.detectChanges(); expect(events).toEqual([ 'child of parent1 onDestroy', 'child of parent2 onDestroy', 'projected1 onDestroy', 'parent1 onDestroy', 'projected2 onDestroy', 'parent2 onDestroy', ]); }); });
{ "end_byte": 101884, "start_byte": 93456, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/lifecycle_spec.ts_101886_104979
scribe('non-regression', () => { it('should call lifecycle hooks for directives active on <ng-template>', () => { let destroyed = false; @Directive({ selector: '[onDestroyDir]', standalone: false, }) class OnDestroyDir { ngOnDestroy() { destroyed = true; } } @Component({ template: `<ng-template [ngIf]="show"> <ng-template onDestroyDir>content</ng-template> </ng-template>`, standalone: false, }) class App { show = true; } TestBed.configureTestingModule({ declarations: [App, OnDestroyDir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(destroyed).toBeFalsy(); fixture.componentInstance.show = false; fixture.detectChanges(); expect(destroyed).toBeTruthy(); }); it('should not throw when calling detectChanges from a setter in the presence of a data binding, ngOnChanges and ngAfterViewInit', () => { const hooks: string[] = []; @Directive({ selector: '[testDir]', standalone: false, }) class TestDirective implements OnChanges, AfterViewInit { constructor(private _changeDetectorRef: ChangeDetectorRef) {} @Input('testDir') set value(_value: any) { this._changeDetectorRef.detectChanges(); } ngOnChanges() { hooks.push('ngOnChanges'); } ngAfterViewInit() { hooks.push('ngAfterViewInit'); } } @Component({ template: `<div [testDir]="value">{{value}}</div>`, standalone: false, }) class App { value = 1; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); expect(() => fixture.detectChanges()).not.toThrow(); expect(hooks).toEqual(['ngOnChanges', 'ngAfterViewInit']); expect(fixture.nativeElement.textContent.trim()).toBe('1'); }); it('should call hooks in the correct order when calling detectChanges in a setter', () => { const hooks: string[] = []; @Directive({ selector: '[testDir]', standalone: false, }) class TestDirective implements OnChanges, DoCheck, AfterViewInit { constructor(private _changeDetectorRef: ChangeDetectorRef) {} @Input('testDir') set value(_value: any) { this._changeDetectorRef.detectChanges(); } ngOnChanges() { hooks.push('ngOnChanges'); } ngDoCheck() { hooks.push('ngDoCheck'); } ngAfterViewInit() { hooks.push('ngAfterViewInit'); } } @Component({ template: `<div [testDir]="value">{{value}}</div>`, standalone: false, }) class App { value = 1; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); expect(() => fixture.detectChanges()).not.toThrow(); expect(hooks).toEqual(['ngOnChanges', 'ngDoCheck', 'ngAfterViewInit']); expect(fixture.nativeElement.textContent.trim()).toBe('1'); }); });
{ "end_byte": 104979, "start_byte": 101886, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/lifecycle_spec.ts" }
angular/packages/core/test/acceptance/pending_tasks_spec.ts_0_5023
/** * @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, PendingTasks} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {EMPTY, firstValueFrom, of} from 'rxjs'; import {filter, map, take, withLatestFrom} from 'rxjs/operators'; import {PendingTasksInternal} from '../../src/pending_tasks'; describe('PendingTasks', () => { it('should wait until all tasks are completed', async () => { const pendingTasks = TestBed.inject(PendingTasksInternal); const taskA = pendingTasks.add(); const taskB = pendingTasks.add(); const taskC = pendingTasks.add(); pendingTasks.remove(taskA); pendingTasks.remove(taskB); pendingTasks.remove(taskC); expect(await hasPendingTasks(pendingTasks)).toBeFalse(); }); it('should allow calls to remove the same task multiple times', async () => { const pendingTasks = TestBed.inject(PendingTasksInternal); expect(await hasPendingTasks(pendingTasks)).toBeFalse(); const taskA = pendingTasks.add(); expect(await hasPendingTasks(pendingTasks)).toBeTrue(); pendingTasks.remove(taskA); pendingTasks.remove(taskA); pendingTasks.remove(taskA); expect(await hasPendingTasks(pendingTasks)).toBeFalse(); }); it('should be tolerant to removal of non-existent ids', async () => { const pendingTasks = TestBed.inject(PendingTasksInternal); expect(await hasPendingTasks(pendingTasks)).toBeFalse(); pendingTasks.remove(Math.random()); pendingTasks.remove(Math.random()); pendingTasks.remove(Math.random()); expect(await hasPendingTasks(pendingTasks)).toBeFalse(); }); it('contributes to applicationRef stableness', async () => { const appRef = TestBed.inject(ApplicationRef); const pendingTasks = TestBed.inject(PendingTasksInternal); const taskA = pendingTasks.add(); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(false); pendingTasks.remove(taskA); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(true); const taskB = pendingTasks.add(); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(false); pendingTasks.remove(taskB); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(true); }); }); describe('public PendingTasks', () => { it('should allow adding and removing tasks influencing stability', async () => { const appRef = TestBed.inject(ApplicationRef); const pendingTasks = TestBed.inject(PendingTasks); const removeTaskA = pendingTasks.add(); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(false); removeTaskA(); // stability is delayed until a tick happens await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(false); TestBed.inject(ApplicationRef).tick(); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(true); }); it('should allow blocking stability with run', async () => { const appRef = TestBed.inject(ApplicationRef); const pendingTasks = TestBed.inject(PendingTasks); let resolveFn: () => void; pendingTasks.run(() => { return new Promise<void>((r) => { resolveFn = r; }); }); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(false); resolveFn!(); await expectAsync(TestBed.inject(ApplicationRef).whenStable()).toBeResolved(); }); it('should return the result of the run function', async () => { const appRef = TestBed.inject(ApplicationRef); const pendingTasks = TestBed.inject(PendingTasks); const result = await pendingTasks.run(async () => { await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(false); return 1; }); expect(result).toBe(1); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(false); await expectAsync(TestBed.inject(ApplicationRef).whenStable()).toBeResolved(); }); xit('should stop blocking stability if run promise rejects', async () => { const appRef = TestBed.inject(ApplicationRef); const pendingTasks = TestBed.inject(PendingTasks); let rejectFn: () => void; const task = pendingTasks.run(() => { return new Promise<void>((_, reject) => { rejectFn = reject; }); }); await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(false); try { rejectFn!(); await task; } catch {} await expectAsync(applicationRefIsStable(appRef)).toBeResolvedTo(true); }); }); function applicationRefIsStable(applicationRef: ApplicationRef) { return firstValueFrom(applicationRef.isStable); } function hasPendingTasks(pendingTasks: PendingTasksInternal): Promise<boolean> { return of(EMPTY) .pipe( withLatestFrom(pendingTasks.hasPendingTasks), map(([_, hasPendingTasks]) => hasPendingTasks), ) .toPromise() as Promise<boolean>; }
{ "end_byte": 5023, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pending_tasks_spec.ts" }
angular/packages/core/test/acceptance/property_interpolation_spec.ts_0_5367
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {of} from 'rxjs'; describe('property interpolation', () => { it('should handle all flavors of interpolated properties', () => { @Component({ template: ` <div title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i{{nine}}j"></div> <div title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i"></div> <div title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h"></div> <div title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g"></div> <div title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f"></div> <div title="a{{one}}b{{two}}c{{three}}d{{four}}e"></div> <div title="a{{one}}b{{two}}c{{three}}d"></div> <div title="a{{one}}b{{two}}c"></div> <div title="a{{one}}b"></div> <div title="{{one}}"></div> `, standalone: false, }) class App { one = 1; two = 2; three = 3; four = 4; five = 5; six = 6; seven = 7; eight = 8; nine = 9; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const titles = Array.from( <NodeListOf<HTMLDivElement>>fixture.nativeElement.querySelectorAll('div[title]'), ).map((div: HTMLDivElement) => div.title); expect(titles).toEqual([ 'a1b2c3d4e5f6g7h8i9j', 'a1b2c3d4e5f6g7h8i', 'a1b2c3d4e5f6g7h', 'a1b2c3d4e5f6g', 'a1b2c3d4e5f', 'a1b2c3d4e', 'a1b2c3d', 'a1b2c', 'a1b', '1', ]); }); it('should handle pipes in interpolated properties', () => { @Component({ template: ` <img title="{{(details | async)?.title}}" src="{{(details | async)?.url}}" /> `, standalone: false, }) class App { details = of({ title: 'cool image', url: 'http://somecooldomain:1234/cool_image.png', }); } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const img: HTMLImageElement = fixture.nativeElement.querySelector('img'); expect(img.src).toBe('http://somecooldomain:1234/cool_image.png'); expect(img.title).toBe('cool image'); }); // From https://angular-team.atlassian.net/browse/FW-1287 it('should handle multiple elvis operators', () => { @Component({ template: ` <img src="{{leadSurgeon?.getCommonInfo()?.getPhotoUrl() }}"> `, standalone: false, }) class App { /** Clearly this is a doctor of heavy metals. */ leadSurgeon = { getCommonInfo() { return { getPhotoUrl() { return 'http://somecooldomain:1234/cool_image.png'; }, }; }, }; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const img = fixture.nativeElement.querySelector('img'); expect(img.src).toBe('http://somecooldomain:1234/cool_image.png'); }); it('should not allow unsanitary urls in interpolated properties', () => { @Component({ template: ` <img src="{{naughty}}"> `, standalone: false, }) class App { naughty = 'javascript:alert("haha, I am taking over your computer!!!");'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const img: HTMLImageElement = fixture.nativeElement.querySelector('img'); expect(img.src.indexOf('unsafe:')).toBe(0); }); it('should not allow unsanitary urls in interpolated properties, even if you are tricky', () => { @Component({ template: ` <img src="{{ja}}{{va}}script:{{naughty}}"> `, standalone: false, }) class App { ja = 'ja'; va = 'va'; naughty = 'alert("I am a h4xx0rz1!!");'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const img = fixture.nativeElement.querySelector('img'); expect(img.src.indexOf('unsafe:')).toBe(0); }); it('should handle interpolations with 10+ values', () => { @Component({ selector: 'app-comp', template: ` <a href="http://g.com/?one={{'1'}}&two={{'2'}}&three={{'3'}}&four={{'4'}}&five={{'5'}}&six={{'6'}}&seven={{'7'}}&eight={{'8'}}&nine={{'9'}}&ten={{'10'}}">link2</a>`, standalone: false, }) class AppComp {} TestBed.configureTestingModule({declarations: [AppComp]}); const fixture = TestBed.createComponent(AppComp); fixture.detectChanges(); const anchor = fixture.debugElement.query(By.css('a')).nativeElement; expect(anchor.getAttribute('href')).toEqual( `http://g.com/?one=1&two=2&three=3&four=4&five=5&six=6&seven=7&eight=8&nine=9&ten=10`, ); });
{ "end_byte": 5367, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/property_interpolation_spec.ts" }
angular/packages/core/test/acceptance/property_interpolation_spec.ts_5371_7899
it('should support the chained use cases of propertyInterpolate instructions', () => { // The below *just happens* to have two attributes in a row that have the same interpolation // count. @Component({ template: ` <img title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i{{nine}}j" alt="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i{{nine}}j"/> <img title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i" alt="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i"/> <img title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h" alt="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h"/> <img title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g" alt="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g"/> <img title="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f" alt="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f"/> <img title="a{{one}}b{{two}}c{{three}}d{{four}}e" alt="a{{one}}b{{two}}c{{three}}d{{four}}e"/> <img title="a{{one}}b{{two}}c{{three}}d" alt="a{{one}}b{{two}}c{{three}}d"/> <img title="a{{one}}b{{two}}c" alt="a{{one}}b{{two}}c"/> <img title="a{{one}}b" alt="a{{one}}b"/> <img title="{{one}}" alt="{{one}}"/> `, standalone: false, }) class AppComp { one = 1; two = 2; three = 3; four = 4; five = 5; six = 6; seven = 7; eight = 8; nine = 9; } TestBed.configureTestingModule({declarations: [AppComp]}); const fixture = TestBed.createComponent(AppComp); fixture.detectChanges(); const titles = Array.from( <NodeListOf<HTMLImageElement>>fixture.nativeElement.querySelectorAll('img[title]'), ).map((img: HTMLImageElement) => img.title); expect(titles).toEqual([ 'a1b2c3d4e5f6g7h8i9j', 'a1b2c3d4e5f6g7h8i', 'a1b2c3d4e5f6g7h', 'a1b2c3d4e5f6g', 'a1b2c3d4e5f', 'a1b2c3d4e', 'a1b2c3d', 'a1b2c', 'a1b', '1', ]); const others = Array.from( <NodeListOf<HTMLImageElement>>fixture.nativeElement.querySelectorAll('img[alt]'), ).map((img: HTMLImageElement) => img.alt); expect(others).toEqual([ 'a1b2c3d4e5f6g7h8i9j', 'a1b2c3d4e5f6g7h8i', 'a1b2c3d4e5f6g7h', 'a1b2c3d4e5f6g', 'a1b2c3d4e5f', 'a1b2c3d4e', 'a1b2c3d', 'a1b2c', 'a1b', '1', ]); }); });
{ "end_byte": 7899, "start_byte": 5371, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/property_interpolation_spec.ts" }
angular/packages/core/test/acceptance/standalone_injector_spec.ts_0_3161
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Component, createComponent, createEnvironmentInjector, EnvironmentInjector, NgModule, ViewChild, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('standalone injector', () => { it('should create one standalone injector for each parent EnvInjector', () => { let counter = 0; class Service { value = counter++; } @NgModule({providers: [Service]}) class ModuleWithAService {} @Component({ selector: 'standalone', standalone: true, imports: [ModuleWithAService], template: `({{service.value}})`, }) class TestComponent { constructor(readonly service: Service) {} } @Component({ selector: 'app', template: `<ng-template #insert></ng-template>`, standalone: false, }) class AppComponent { @ViewChild('insert', {static: true, read: ViewContainerRef}) vcRef!: ViewContainerRef; createComponent(envInjector?: EnvironmentInjector): void { this.vcRef.createComponent(TestComponent, {environmentInjector: envInjector}); } } const fixture = TestBed.createComponent(AppComponent); const currEnvInjector = TestBed.inject(EnvironmentInjector); fixture.componentInstance.createComponent(currEnvInjector); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)'); // inserting the same standalone component second time and asserting that no new injector / // service instance gets created fixture.componentInstance.createComponent(currEnvInjector); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)(0)'); // inserting with a different EnvInjector as a parent should trigger a new service instance // creation fixture.componentInstance.createComponent(createEnvironmentInjector([], currEnvInjector)); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(0)(0)(1)'); }); it('should create a standalone Injector for ComponentRefs that are not inserted anywhere', () => { class Service { value = 'Service value'; } @NgModule({providers: [Service]}) class ModuleWithAService {} @Component({ selector: 'standalone', standalone: true, imports: [ModuleWithAService], template: `{{service.value}}`, }) class DynamicComponent { constructor(readonly service: Service) {} } @Component({ standalone: false, }) class AppComponent {} const fixture = TestBed.createComponent(AppComponent); const environmentInjector = createEnvironmentInjector( [Service], TestBed.inject(EnvironmentInjector), ); const componentRef = createComponent(DynamicComponent, {environmentInjector}); componentRef.changeDetectorRef.detectChanges(); expect(componentRef.location.nativeElement.textContent).toBe('Service value'); }); });
{ "end_byte": 3161, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/standalone_injector_spec.ts" }
angular/packages/core/test/acceptance/attributes_spec.ts_0_6623
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By, DomSanitizer, SafeUrl} from '@angular/platform-browser'; describe('attribute creation', () => { it('should create an element', () => { @Component({ template: `<div id="test" title="Hello"></div>`, standalone: false, }) class Comp {} TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const div = fixture.debugElement.query(By.css('div')).nativeElement; expect(div.id).toEqual('test'); expect(div.title).toEqual('Hello'); }); it('should allow for setting xlink namespaced attributes', () => { @Component({ template: `<div id="test" xlink:href="bar" title="Hello"></div>`, standalone: false, }) class Comp {} TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const div = fixture.debugElement.query(By.css('div')).nativeElement; const attrs = div.attributes; expect(attrs['id'].name).toEqual('id'); expect(attrs['id'].namespaceURI).toEqual(null); expect(attrs['id'].value).toEqual('test'); expect(attrs['xlink:href'].name).toEqual('xlink:href'); expect(attrs['xlink:href'].namespaceURI).toEqual('http://www.w3.org/1999/xlink'); expect(attrs['xlink:href'].value).toEqual('bar'); expect(attrs['title'].name).toEqual('title'); expect(attrs['title'].namespaceURI).toEqual(null); expect(attrs['title'].value).toEqual('Hello'); }); }); describe('attribute binding', () => { it('should set attribute values', () => { @Component({ template: `<a [attr.href]="url"></a>`, standalone: false, }) class Comp { url = 'https://angular.io/robots.txt'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const a = fixture.debugElement.query(By.css('a')).nativeElement; // NOTE: different browsers will add `//` into the URI. expect(a.href).toEqual('https://angular.io/robots.txt'); }); it('should be able to bind multiple attribute values per element', () => { @Component({ template: `<a [attr.id]="id" [attr.href]="url" [attr.tabindex]="'-1'"></a>`, standalone: false, }) class Comp { url = 'https://angular.io/robots.txt'; id = 'my-link'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const a = fixture.debugElement.query(By.css('a')).nativeElement; // NOTE: different browsers will add `//` into the URI. expect(a.getAttribute('href')).toBe('https://angular.io/robots.txt'); expect(a.getAttribute('id')).toBe('my-link'); expect(a.getAttribute('tabindex')).toBe('-1'); }); it('should be able to bind multiple attributes in the presence of other bindings', () => { @Component({ template: `<a [id]="id" [attr.href]="url" [title]="'hello'"></a>`, standalone: false, }) class Comp { url = 'https://angular.io/robots.txt'; id = 'my-link'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const a = fixture.debugElement.query(By.css('a')).nativeElement; // NOTE: different browsers will add `//` into the URI. expect(a.getAttribute('href')).toBe('https://angular.io/robots.txt'); expect(a.id).toBe('my-link'); expect(a.getAttribute('title')).toBe('hello'); }); it('should be able to bind attributes with interpolations', () => { @Component({ template: ` <button attr.id="my-{{id}}-button" [attr.title]="title" attr.tabindex="{{1 + 3 + 7}}"></button>`, standalone: false, }) class Comp { title = 'hello'; id = 'custom'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const button = fixture.debugElement.query(By.css('button')).nativeElement; expect(button.getAttribute('id')).toBe('my-custom-button'); expect(button.getAttribute('tabindex')).toBe('11'); expect(button.getAttribute('title')).toBe('hello'); }); it('should be able to bind attributes both to parent and child nodes', () => { @Component({ template: ` <button attr.id="my-{{id}}-button" [attr.title]="title" attr.tabindex="{{1 + 3 + 7}}"> <span attr.title="span-{{title}}" id="custom-span" [attr.tabindex]="-1"></span> </button> `, standalone: false, }) class Comp { title = 'hello'; id = 'custom'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const button = fixture.debugElement.query(By.css('button')).nativeElement; const span = fixture.debugElement.query(By.css('span')).nativeElement; expect(button.getAttribute('id')).toBe('my-custom-button'); expect(button.getAttribute('tabindex')).toBe('11'); expect(button.getAttribute('title')).toBe('hello'); expect(span.getAttribute('id')).toBe('custom-span'); expect(span.getAttribute('tabindex')).toBe('-1'); expect(span.getAttribute('title')).toBe('span-hello'); }); it('should sanitize attribute values', () => { @Component({ template: `<a [attr.href]="badUrl"></a>`, standalone: false, }) class Comp { badUrl: string | SafeUrl = 'javascript:true'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const a = fixture.debugElement.query(By.css('a')).nativeElement; // NOTE: different browsers will add `//` into the URI. expect(a.href.indexOf('unsafe:')).toBe(0); const domSanitizer: DomSanitizer = TestBed.inject(DomSanitizer); fixture.componentInstance.badUrl = domSanitizer.bypassSecurityTrustUrl( 'javascript:alert("this is fine")', ); fixture.detectChanges(); // should not start with `unsafe:`. expect(a.href.indexOf('unsafe:')).toBe(-1); }); });
{ "end_byte": 6623, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/attributes_spec.ts" }
angular/packages/core/test/acceptance/attributes_spec.ts_6625_8089
describe('attribute interpolation', () => { it('should handle all varieties of interpolation', () => { @Component({ template: ` <div attr.title="a{{a}}b{{b}}c{{c}}d{{d}}e{{e}}f{{f}}g{{g}}h{{h}}i{{i}}j"></div> <div attr.title="a{{a}}b{{b}}c{{c}}d{{d}}e{{e}}f{{f}}g{{g}}h{{h}}i"></div> <div attr.title="a{{a}}b{{b}}c{{c}}d{{d}}e{{e}}f{{f}}g{{g}}h"></div> <div attr.title="a{{a}}b{{b}}c{{c}}d{{d}}e{{e}}f{{f}}g"></div> <div attr.title="a{{a}}b{{b}}c{{c}}d{{d}}e{{e}}f"></div> <div attr.title="a{{a}}b{{b}}c{{c}}d{{d}}e"></div> <div attr.title="a{{a}}b{{b}}c{{c}}d"></div> <div attr.title="a{{a}}b{{b}}c"></div> <div attr.title="a{{a}}b"></div> <div attr.title="{{a}}"></div> `, standalone: false, }) class App { a = 1; b = 2; c = 3; d = 4; e = 5; f = 6; g = 7; h = 8; i = 9; } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const divs = fixture.debugElement.queryAll(By.css('div[title]')); expect(divs.map((el) => el.nativeElement.getAttribute('title'))).toEqual([ 'a1b2c3d4e5f6g7h8i9j', 'a1b2c3d4e5f6g7h8i', 'a1b2c3d4e5f6g7h', 'a1b2c3d4e5f6g', 'a1b2c3d4e5f', 'a1b2c3d4e', 'a1b2c3d', 'a1b2c', 'a1b', '1', ]); }); });
{ "end_byte": 8089, "start_byte": 6625, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/attributes_spec.ts" }
angular/packages/core/test/acceptance/providers_spec.ts_0_2040
/** * @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 {CommonModule} from '@angular/common'; import { Component, Directive, forwardRef, Inject, Injectable, InjectionToken, Injector, NgModule, Optional, } from '@angular/core'; import {leaveView, specOnlyIsInstructionStateEmpty} from '@angular/core/src/render3/state'; import {inject, TestBed, waitForAsync} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('providers', () => { describe('inheritance', () => { it('should NOT inherit providers', () => { const SOME_DIRS = new InjectionToken('someDirs'); @Directive({ selector: '[super-dir]', providers: [{provide: SOME_DIRS, useClass: SuperDirective, multi: true}], standalone: false, }) class SuperDirective {} @Directive({ selector: '[sub-dir]', providers: [{provide: SOME_DIRS, useClass: SubDirective, multi: true}], standalone: false, }) class SubDirective extends SuperDirective {} @Directive({ selector: '[other-dir]', standalone: false, }) class OtherDirective { constructor(@Inject(SOME_DIRS) public dirs: any) {} } @Component({ selector: 'app-comp', template: `<div other-dir sub-dir></div>`, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [SuperDirective, SubDirective, OtherDirective, App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const otherDir = fixture.debugElement.query(By.css('div')).injector.get(OtherDirective); expect(otherDir.dirs.length).toEqual(1); expect(otherDir.dirs[0] instanceof SubDirective).toBe(true); }); });
{ "end_byte": 2040, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/providers_spec.ts" }
angular/packages/core/test/acceptance/providers_spec.ts_2044_10859
describe('lifecycles', () => { it('should inherit ngOnDestroy hooks on providers', () => { const logs: string[] = []; @Injectable() class SuperInjectableWithDestroyHook { ngOnDestroy() { logs.push('OnDestroy'); } } @Injectable() class SubInjectableWithDestroyHook extends SuperInjectableWithDestroyHook {} @Component({ template: '', providers: [SubInjectableWithDestroyHook], standalone: false, }) class App { constructor(foo: SubInjectableWithDestroyHook) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy']); }); it('should not call ngOnDestroy for providers that have not been requested', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHook { ngOnDestroy() { logs.push('OnDestroy'); } } @Component({ template: '', providers: [InjectableWithDestroyHook], standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual([]); }); it('should only call ngOnDestroy once for multiple instances', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHook { ngOnDestroy() { logs.push('OnDestroy'); } } @Component({ selector: 'my-cmp', template: '', standalone: false, }) class MyComponent { constructor(foo: InjectableWithDestroyHook) {} } @Component({ template: ` <my-cmp></my-cmp> <my-cmp></my-cmp> `, providers: [InjectableWithDestroyHook], standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy']); }); it('should call ngOnDestroy when providing same token via useClass', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHook { ngOnDestroy() { logs.push('OnDestroy'); } } @Component({ template: '', providers: [{provide: InjectableWithDestroyHook, useClass: InjectableWithDestroyHook}], standalone: false, }) class App { constructor(foo: InjectableWithDestroyHook) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy']); }); it('should only call ngOnDestroy of value when providing via useClass', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHookToken { ngOnDestroy() { logs.push('OnDestroy Token'); } } @Injectable() class InjectableWithDestroyHookValue { ngOnDestroy() { logs.push('OnDestroy Value'); } } @Component({ template: '', providers: [ {provide: InjectableWithDestroyHookToken, useClass: InjectableWithDestroyHookValue}, ], standalone: false, }) class App { constructor(foo: InjectableWithDestroyHookToken) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy Value']); }); it('should only call ngOnDestroy of value when providing via useExisting', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHookToken { ngOnDestroy() { logs.push('OnDestroy Token'); } } @Injectable() class InjectableWithDestroyHookExisting { ngOnDestroy() { logs.push('OnDestroy Existing'); } } @Component({ template: '', providers: [ InjectableWithDestroyHookExisting, {provide: InjectableWithDestroyHookToken, useExisting: InjectableWithDestroyHookExisting}, ], standalone: false, }) class App { constructor( foo1: InjectableWithDestroyHookExisting, foo2: InjectableWithDestroyHookToken, ) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy Existing']); }); it('should invoke ngOnDestroy with the correct context when providing a type provider multiple times on the same node', () => { const resolvedServices: (DestroyService | undefined)[] = []; const destroyContexts: (DestroyService | undefined)[] = []; let parentService: DestroyService | undefined; let childService: DestroyService | undefined; @Injectable() class DestroyService { constructor() { resolvedServices.push(this); } ngOnDestroy() { destroyContexts.push(this); } } @Directive({ selector: '[dir-one]', providers: [DestroyService], standalone: false, }) class DirOne { constructor(service: DestroyService) { childService = service; } } @Directive({ selector: '[dir-two]', providers: [DestroyService], standalone: false, }) class DirTwo { constructor(service: DestroyService) { childService = service; } } @Component({ template: '<div dir-one dir-two></div>', providers: [DestroyService], standalone: false, }) class App { constructor(service: DestroyService) { parentService = service; } } TestBed.configureTestingModule({declarations: [App, DirOne, DirTwo]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(parentService).toBeDefined(); expect(childService).toBeDefined(); expect(parentService).not.toBe(childService); expect(resolvedServices).toEqual([parentService, childService]); expect(destroyContexts).toEqual([parentService, childService]); }); it('should invoke ngOnDestroy with the correct context when providing a class provider multiple times on the same node', () => { const resolvedServices: (DestroyService | undefined)[] = []; const destroyContexts: (DestroyService | undefined)[] = []; const token = new InjectionToken<any>('token'); let parentService: DestroyService | undefined; let childService: DestroyService | undefined; @Injectable() class DestroyService { constructor() { resolvedServices.push(this); } ngOnDestroy() { destroyContexts.push(this); } } @Directive({ selector: '[dir-one]', providers: [{provide: token, useClass: DestroyService}], standalone: false, }) class DirOne { constructor(@Inject(token) service: DestroyService) { childService = service; } } @Directive({ selector: '[dir-two]', providers: [{provide: token, useClass: DestroyService}], standalone: false, }) class DirTwo { constructor(@Inject(token) service: DestroyService) { childService = service; } } @Component({ template: '<div dir-one dir-two></div>', providers: [{provide: token, useClass: DestroyService}], standalone: false, }) class App { constructor(@Inject(token) service: DestroyService) { parentService = service; } } TestBed.configureTestingModule({declarations: [App, DirOne, DirTwo]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(parentService).toBeDefined(); expect(childService).toBeDefined(); expect(parentService).not.toBe(childService); expect(resolvedServices).toEqual([parentService, childService]); expect(destroyContexts).toEqual([parentService, childService]); });
{ "end_byte": 10859, "start_byte": 2044, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/providers_spec.ts" }
angular/packages/core/test/acceptance/providers_spec.ts_10865_20718
describe('ngOnDestroy on multi providers', () => { it('should invoke ngOnDestroy on multi providers with the correct context', () => { const destroyCalls: any[] = []; const SERVICES = new InjectionToken<any>('SERVICES'); @Injectable() class DestroyService { ngOnDestroy() { destroyCalls.push(this); } } @Injectable() class OtherDestroyService { ngOnDestroy() { destroyCalls.push(this); } } @Component({ template: '<div></div>', providers: [ {provide: SERVICES, useClass: DestroyService, multi: true}, {provide: SERVICES, useClass: OtherDestroyService, multi: true}, ], standalone: false, }) class App { constructor(@Inject(SERVICES) s: any) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toEqual([ jasmine.any(DestroyService), jasmine.any(OtherDestroyService), ]); }); it('should invoke destroy hooks on multi providers with the correct context, if only some have a destroy hook', () => { const destroyCalls: any[] = []; const SERVICES = new InjectionToken<any>('SERVICES'); @Injectable() class Service1 {} @Injectable() class Service2 { ngOnDestroy() { destroyCalls.push(this); } } @Injectable() class Service3 {} @Injectable() class Service4 { ngOnDestroy() { destroyCalls.push(this); } } @Component({ template: '<div></div>', providers: [ {provide: SERVICES, useClass: Service1, multi: true}, {provide: SERVICES, useClass: Service2, multi: true}, {provide: SERVICES, useClass: Service3, multi: true}, {provide: SERVICES, useClass: Service4, multi: true}, ], standalone: false, }) class App { constructor(@Inject(SERVICES) s: any) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toEqual([jasmine.any(Service2), jasmine.any(Service4)]); }); it('should not invoke ngOnDestroy on multi providers created via useFactory', () => { let destroyCalls = 0; const SERVICES = new InjectionToken<any>('SERVICES'); @Injectable() class DestroyService { ngOnDestroy() { destroyCalls++; } } @Injectable() class OtherDestroyService { ngOnDestroy() { destroyCalls++; } } @Component({ template: '<div></div>', providers: [ {provide: SERVICES, useFactory: () => new DestroyService(), multi: true}, {provide: SERVICES, useFactory: () => new OtherDestroyService(), multi: true}, ], standalone: false, }) class App { constructor(@Inject(SERVICES) s: any) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toBe(0); }); }); it('should call ngOnDestroy if host component is destroyed', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHookToken { ngOnDestroy() { logs.push('OnDestroy Token'); } } @Component({ selector: 'comp-with-provider', template: '', providers: [InjectableWithDestroyHookToken], standalone: false, }) class CompWithProvider { constructor(token: InjectableWithDestroyHookToken) {} } @Component({ selector: 'app', template: '<comp-with-provider *ngIf="condition"></comp-with-provider>', standalone: false, }) class App { condition = true; } TestBed.configureTestingModule({ declarations: [App, CompWithProvider], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.condition = false; fixture.detectChanges(); expect(logs).toEqual(['OnDestroy Token']); }); }); describe('components and directives', () => { class MyService { value = 'some value'; } @Component({ selector: 'my-comp', template: ``, standalone: false, }) class MyComp { constructor(public svc: MyService) {} } @Directive({ selector: '[some-dir]', standalone: false, }) class MyDir { constructor(public svc: MyService) {} } it('should support providing components in tests without @Injectable', () => { @Component({ selector: 'test-comp', template: '<my-comp></my-comp>', standalone: false, }) class TestComp {} TestBed.configureTestingModule({ declarations: [TestComp, MyComp], // providing MyComp is unnecessary but it shouldn't throw providers: [MyComp, MyService], }); const fixture = TestBed.createComponent(TestComp); const myCompInstance = fixture.debugElement.query(By.css('my-comp')).injector.get(MyComp); expect(myCompInstance.svc.value).toEqual('some value'); }); it('should support providing directives in tests without @Injectable', () => { @Component({ selector: 'test-comp', template: '<div some-dir></div>', standalone: false, }) class TestComp {} TestBed.configureTestingModule({ declarations: [TestComp, MyDir], // providing MyDir is unnecessary but it shouldn't throw providers: [MyDir, MyService], }); const fixture = TestBed.createComponent(TestComp); const myCompInstance = fixture.debugElement.query(By.css('div')).injector.get(MyDir); expect(myCompInstance.svc.value).toEqual('some value'); }); // TODO(alxhub): find a way to isolate this test from running in a dirty // environment where a current LView exists (probably from some other test // bootstrapping and then not cleaning up). xdescribe('injection without bootstrapping', () => { beforeEach(() => { // Maybe something like this? while (!specOnlyIsInstructionStateEmpty()) { leaveView(); } TestBed.configureTestingModule({declarations: [MyComp], providers: [MyComp, MyService]}); }); it('should support injecting without bootstrapping', waitForAsync( inject([MyComp, MyService], (comp: MyComp, service: MyService) => { expect(comp.svc.value).toEqual('some value'); }), )); }); }); describe('forward refs', () => { it('should support forward refs in provider deps', () => { class MyService { constructor(public dep: {value: string}) {} } class OtherService { value = 'one'; } @Component({ selector: 'app-comp', template: ``, standalone: false, }) class AppComp { constructor(public myService: MyService) {} } @NgModule({ providers: [ OtherService, { provide: MyService, useFactory: (dep: {value: string}) => new MyService(dep), deps: [forwardRef(() => OtherService)], }, ], declarations: [AppComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); const fixture = TestBed.createComponent(AppComp); expect(fixture.componentInstance.myService.dep.value).toBe('one'); }); it('should support forward refs in useClass when impl version is also provided', () => { @Injectable({providedIn: 'root', useClass: forwardRef(() => SomeProviderImpl)}) abstract class SomeProvider {} @Injectable() class SomeProviderImpl extends SomeProvider {} @Component({ selector: 'my-app', template: '', standalone: false, }) class App { constructor(public foo: SomeProvider) {} } // We don't configure the `SomeProvider` in the TestingModule so that it uses the // tree-shakable provider given in the `@Injectable` decorator above, which makes use of the // `forwardRef()`. TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.foo).toBeInstanceOf(SomeProviderImpl); }); it('should support forward refs in useClass when token is provided', () => { @Injectable({providedIn: 'root'}) abstract class SomeProvider {} @Injectable() class SomeProviderImpl extends SomeProvider {} @Component({ selector: 'my-app', template: '', standalone: false, }) class App { constructor(public foo: SomeProvider) {} } TestBed.configureTestingModule({ declarations: [App], providers: [{provide: SomeProvider, useClass: forwardRef(() => SomeProviderImpl)}], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.foo).toBeInstanceOf(SomeProviderImpl); }); });
{ "end_byte": 20718, "start_byte": 10865, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/providers_spec.ts" }
angular/packages/core/test/acceptance/providers_spec.ts_20722_23349
describe('flags', () => { class MyService { constructor(public value: OtherService | null) {} } class OtherService {} it('should support Optional flag in deps', () => { const injector = Injector.create({ providers: [{provide: MyService, deps: [[new Optional(), OtherService]]}], }); expect(injector.get(MyService).value).toBe(null); }); it('should support Optional flag in deps without instantiating it', () => { const injector = Injector.create({ providers: [{provide: MyService, deps: [[Optional, OtherService]]}], }); expect(injector.get(MyService).value).toBe(null); }); }); describe('view providers', () => { it('should have access to viewProviders within the same component', () => { @Component({ selector: 'comp', template: '{{s}}-{{n}}', providers: [{provide: Number, useValue: 1, multi: true}], viewProviders: [ {provide: String, useValue: 'bar'}, {provide: Number, useValue: 2, multi: true}, ], standalone: false, }) class Comp { constructor( private s: String, private n: Number, ) {} } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('bar-1,2'); }); it('should have access to viewProviders of the host component', () => { @Component({ selector: 'repeated', template: '[{{s}}-{{n}}]', standalone: false, }) class Repeated { constructor( private s: String, private n: Number, ) {} } @Component({ template: ` <div> <ng-container *ngFor="let item of items"> <repeated></repeated> </ng-container> </div> `, providers: [{provide: Number, useValue: 1, multi: true}], viewProviders: [ {provide: String, useValue: 'foo'}, {provide: Number, useValue: 2, multi: true}, ], standalone: false, }) class ComponentWithProviders { items = [1, 2, 3]; } TestBed.configureTestingModule({ declarations: [ComponentWithProviders, Repeated], imports: [CommonModule], }); const fixture = TestBed.createComponent(ComponentWithProviders); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('[foo-1,2][foo-1,2][foo-1,2]'); }); }); });
{ "end_byte": 23349, "start_byte": 20722, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/providers_spec.ts" }
angular/packages/core/test/acceptance/profiler_spec.ts_0_6717
/** * @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 {setProfiler} from '@angular/core/src/render3/profiler'; import {ProfilerEvent} from '@angular/core/src/render3/profiler_types'; import {TestBed} from '@angular/core/testing'; import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, ErrorHandler, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, ViewChild, } from '../../src/core'; describe('profiler', () => { class Profiler { profile() {} } let profilerSpy: jasmine.Spy; beforeEach(() => { const profiler = new Profiler(); profilerSpy = spyOn(profiler, 'profile').and.callThrough(); setProfiler(profiler.profile); }); afterAll(() => setProfiler(null)); function findProfilerCall(condition: ProfilerEvent | ((args: any[]) => boolean)) { let predicate: (args: any[]) => boolean = (_) => true; if (typeof condition !== 'function') { predicate = (args: any[]) => args[0] === condition; } else { predicate = condition; } return profilerSpy.calls .all() .map((call: any) => call.args) .find(predicate); } describe('change detection hooks', () => { it('should call the profiler for creation and change detection', () => { @Component({ selector: 'my-comp', template: '<button (click)="onClick()"></button>', standalone: false, }) class MyComponent { onClick() {} } TestBed.configureTestingModule({declarations: [MyComponent]}); const fixture = TestBed.createComponent(MyComponent); expect(profilerSpy).toHaveBeenCalled(); const templateCreateStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.TemplateCreateStart && args[1] === fixture.componentInstance, ); const templateCreateEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.TemplateCreateEnd && args[1] === fixture.componentInstance, ); expect(templateCreateStart).toBeTruthy(); expect(templateCreateEnd).toBeTruthy(); fixture.detectChanges(); const templateUpdateStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.TemplateUpdateStart && args[1] === fixture.componentInstance, ); const templateUpdateEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.TemplateUpdateEnd && args[1] === fixture.componentInstance, ); expect(templateUpdateStart).toBeTruthy(); expect(templateUpdateEnd).toBeTruthy(); }); it('should invoke the profiler when the template throws', () => { @Component({selector: 'my-comp', template: '{{ throw() }}', standalone: false}) class MyComponent { throw() { throw new Error(); } } TestBed.configureTestingModule({declarations: [MyComponent]}); let myComp: MyComponent; expect(() => { const fixture = TestBed.createComponent(MyComponent); myComp = fixture.componentInstance; fixture.detectChanges(); }).toThrow(); expect(profilerSpy).toHaveBeenCalled(); const templateCreateStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.TemplateCreateStart && args[1] === myComp, ); const templateCreateEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.TemplateCreateEnd && args[1] === myComp, ); expect(templateCreateStart).toBeTruthy(); expect(templateCreateEnd).toBeTruthy(); }); }); describe('outputs and events', () => { it('should invoke the profiler on event handler', () => { @Component({ selector: 'my-comp', template: '<button (click)="onClick()"></button>', standalone: false, }) class MyComponent { onClick() {} } TestBed.configureTestingModule({declarations: [MyComponent]}); const fixture = TestBed.createComponent(MyComponent); const myComp = fixture.componentInstance; const clickSpy = spyOn(myComp, 'onClick'); const button = fixture.nativeElement.querySelector('button')!; button.click(); expect(clickSpy).toHaveBeenCalled(); const outputStart = findProfilerCall(ProfilerEvent.OutputStart); const outputEnd = findProfilerCall(ProfilerEvent.OutputEnd); expect(outputStart[1]).toEqual(myComp!); expect(outputEnd[1]).toEqual(myComp!); }); it('should invoke the profiler on event handler even when it throws', () => { @Component({ selector: 'my-comp', template: '<button (click)="onClick()"></button>', standalone: false, }) class MyComponent { onClick() { throw new Error(); } } const handler = new ErrorHandler(); const errorSpy = spyOn(handler, 'handleError'); TestBed.configureTestingModule({ declarations: [MyComponent], providers: [{provide: ErrorHandler, useValue: handler}], }); const fixture = TestBed.createComponent(MyComponent); const myComp = fixture.componentInstance; const button = fixture.nativeElement.querySelector('button')!; button.click(); expect(errorSpy).toHaveBeenCalled(); const outputStart = findProfilerCall(ProfilerEvent.OutputStart); const outputEnd = findProfilerCall(ProfilerEvent.OutputEnd); expect(outputStart[1]).toEqual(myComp!); expect(outputEnd[1]).toEqual(myComp!); }); it('should invoke the profiler on output handler execution', async () => { @Component({selector: 'child', template: '', standalone: false}) class Child { @Output() childEvent = new EventEmitter(); } @Component({ selector: 'my-comp', template: '<child (childEvent)="onEvent()"></child>', standalone: false, }) class MyComponent { @ViewChild(Child) child!: Child; onEvent() {} } TestBed.configureTestingModule({declarations: [MyComponent, Child]}); const fixture = TestBed.createComponent(MyComponent); const myComp = fixture.componentInstance; fixture.detectChanges(); myComp.child!.childEvent.emit(); const outputStart = findProfilerCall(ProfilerEvent.OutputStart); const outputEnd = findProfilerCall(ProfilerEvent.OutputEnd); expect(outputStart[1]).toEqual(myComp!); expect(outputEnd[1]).toEqual(myComp!); }); });
{ "end_byte": 6717, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/profiler_spec.ts" }
angular/packages/core/test/acceptance/profiler_spec.ts_6721_13311
describe('lifecycle hooks', () => { it('should call the profiler on lifecycle execution', () => { class Service implements OnDestroy { ngOnDestroy() {} } @Component({ selector: 'my-comp', template: '{{prop}}', providers: [Service], standalone: false, }) class MyComponent implements OnInit, AfterViewInit, AfterViewChecked, AfterContentInit, AfterContentChecked, OnChanges, DoCheck, OnDestroy { @Input() prop = 1; constructor(private service: Service) {} ngOnInit() {} ngDoCheck() {} ngOnDestroy() {} ngOnChanges() {} ngAfterViewInit() {} ngAfterViewChecked() {} ngAfterContentInit() {} ngAfterContentChecked() {} } @Component({ selector: 'my-parent', template: '<my-comp [prop]="prop"></my-comp>', standalone: false, }) class MyParent { prop = 1; @ViewChild(MyComponent) child!: MyComponent; } TestBed.configureTestingModule({declarations: [MyParent, MyComponent]}); const fixture = TestBed.createComponent(MyParent); fixture.detectChanges(); const myParent = fixture.componentInstance; const myComp = fixture.componentInstance.child; const ngOnInitStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] === myComp.ngOnInit, ); const ngOnInitEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] === myComp.ngOnInit, ); expect(ngOnInitStart).toBeTruthy(); expect(ngOnInitEnd).toBeTruthy(); const ngOnDoCheckStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] === myComp.ngDoCheck, ); const ngOnDoCheckEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] === myComp.ngDoCheck, ); expect(ngOnDoCheckStart).toBeTruthy(); expect(ngOnDoCheckEnd).toBeTruthy(); const ngAfterViewInitStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] === myComp.ngAfterViewInit, ); const ngAfterViewInitEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] === myComp.ngAfterViewInit, ); expect(ngAfterViewInitStart).toBeTruthy(); expect(ngAfterViewInitEnd).toBeTruthy(); const ngAfterViewCheckedStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] === myComp.ngAfterViewChecked, ); const ngAfterViewCheckedEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] === myComp.ngAfterViewChecked, ); expect(ngAfterViewCheckedStart).toBeTruthy(); expect(ngAfterViewCheckedEnd).toBeTruthy(); const ngAfterContentInitStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] === myComp.ngAfterContentInit, ); const ngAfterContentInitEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] === myComp.ngAfterContentInit, ); expect(ngAfterContentInitStart).toBeTruthy(); expect(ngAfterContentInitEnd).toBeTruthy(); const ngAfterContentCheckedStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] === myComp.ngAfterContentChecked, ); const ngAfterContentChecked = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] === myComp.ngAfterContentChecked, ); expect(ngAfterContentCheckedStart).toBeTruthy(); expect(ngAfterContentChecked).toBeTruthy(); // Verify we call `ngOnChanges` and the corresponding profiler hooks const onChangesSpy = spyOn(myComp, 'ngOnChanges'); profilerSpy.calls.reset(); myParent.prop = 2; fixture.detectChanges(); const ngOnChangesStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] && args[2].name && args[2].name.indexOf('OnChangesHook') >= 0, ); const ngOnChangesEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] && args[2].name && args[2].name.indexOf('OnChangesHook') >= 0, ); expect(onChangesSpy).toHaveBeenCalled(); expect(ngOnChangesStart).toBeTruthy(); expect(ngOnChangesEnd).toBeTruthy(); fixture.destroy(); const ngOnDestroyStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] === myComp.ngOnDestroy, ); const ngOnDestroyEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] === myComp.ngOnDestroy, ); expect(ngOnDestroyStart).toBeTruthy(); expect(ngOnDestroyEnd).toBeTruthy(); const serviceNgOnDestroyStart = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookStart && args[2] === Service.prototype.ngOnDestroy, ); const serviceNgOnDestroyEnd = findProfilerCall( (args: any[]) => args[0] === ProfilerEvent.LifecycleHookEnd && args[2] === Service.prototype.ngOnDestroy, ); expect(serviceNgOnDestroyStart).toBeTruthy(); expect(serviceNgOnDestroyEnd).toBeTruthy(); }); }); it('should call the profiler on lifecycle execution even after error', () => { @Component({selector: 'my-comp', template: '', standalone: false}) class MyComponent implements OnInit { ngOnInit() { throw new Error(); } } TestBed.configureTestingModule({declarations: [MyComponent]}); const fixture = TestBed.createComponent(MyComponent); expect(() => { fixture.detectChanges(); }).toThrow(); const lifecycleStart = findProfilerCall(ProfilerEvent.LifecycleHookStart); const lifecycleEnd = findProfilerCall(ProfilerEvent.LifecycleHookEnd); expect(lifecycleStart).toBeTruthy(); expect(lifecycleEnd).toBeTruthy(); }); });
{ "end_byte": 13311, "start_byte": 6721, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/profiler_spec.ts" }
angular/packages/core/test/acceptance/ngmodule_scope_spec.ts_0_2307
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, destroyPlatform, NgModule, Pipe, PipeTransform} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {withBody} from '@angular/private/testing'; describe('NgModule scopes', () => { beforeEach(destroyPlatform); afterEach(destroyPlatform); it( 'should apply NgModule scope to a component that extends another component class', withBody('<my-app></my-app>', async () => { // Regression test for https://github.com/angular/angular/issues/37105 // // This test reproduces a scenario that used to fail due to a reentrancy issue in Ivy's JIT // compiler. Extending a component from a decorated baseclass would inadvertently compile // the subclass twice. NgModule scope information would only be present on the initial // compilation, but then overwritten during the second compilation. This meant that the // baseclass did not have a NgModule scope, such that declarations are not available. // // The scenario cannot be tested using TestBed as it influences how NgModule // scopes are applied, preventing the issue from occurring. @Pipe({ name: 'multiply', standalone: false, }) class MultiplyPipe implements PipeTransform { transform(value: number, factor: number): number { return value * factor; } } @Component({ template: '...', standalone: false, }) class BaseComponent {} @Component({ selector: 'my-app', template: 'App - {{ 3 | multiply:2 }}', standalone: false, }) class App extends BaseComponent {} @NgModule({ imports: [BrowserModule], declarations: [App, BaseComponent, MultiplyPipe], bootstrap: [App], }) class Mod {} const ngModuleRef = await platformBrowserDynamic().bootstrapModule(Mod); expect(document.body.textContent).toContain('App - 6'); ngModuleRef.destroy(); }), ); });
{ "end_byte": 2307, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/ngmodule_scope_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_0_8782
/** * @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 {CommonModule} from '@angular/common'; import { Component, ComponentRef, Directive, ElementRef, HostBinding, Input, Renderer2, ViewChild, ViewContainerRef, } from '@angular/core'; import {bypassSanitizationTrustStyle} from '@angular/core/src/sanitization/bypass'; import {ngDevModeResetPerfCounters} from '@angular/core/src/util/ng_dev_mode'; import {TestBed} from '@angular/core/testing'; import { getElementClasses, getElementStyles, getSortedClassName, getSortedStyle, } from '@angular/core/testing/src/styling'; import {By, DomSanitizer, SafeStyle} from '@angular/platform-browser'; import {expectPerfCounters} from '@angular/private/testing'; describe('styling', () => { beforeEach(ngDevModeResetPerfCounters); describe('apply in prioritization order', () => { it('should perform static bindings', () => { @Component({ template: `<div class="STATIC" style="color: blue"></div>`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const staticDiv = fixture.nativeElement.querySelectorAll('div')[0]; expect(getSortedClassName(staticDiv)).toEqual('STATIC'); expect(getSortedStyle(staticDiv)).toEqual('color: blue;'); }); it('should perform prop bindings', () => { @Component({ template: `<div [class.dynamic]="true" [style.color]="'blue'" [style.width.px]="100"></div>`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(getSortedClassName(div)).toEqual('dynamic'); expect(getSortedStyle(div)).toEqual('color: blue; width: 100px;'); }); it('should perform map bindings', () => { @Component({ template: `<div [class]="{dynamic: true}" [style]="{color: 'blue', width: '100px'}"></div>`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(getSortedClassName(div)).toEqual('dynamic'); expect(getSortedStyle(div)).toEqual('color: blue; width: 100px;'); }); it('should perform interpolation bindings', () => { @Component({ template: `<div class="static {{'dynamic'}}" style.color="blu{{'e'}}" style="width: {{'100'}}px"></div>`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(getSortedClassName(div)).toEqual('dynamic static'); expect(getSortedStyle(div)).toEqual('color: blue; width: 100px;'); }); it('should support hostBindings', () => { @Component({ template: `<div my-host-bindings-2 my-host-bindings-1 class="STATIC" style="color: blue"></div>`, standalone: false, }) class Cmp {} @Directive({ selector: '[my-host-bindings-1]', host: {'class': 'HOST_STATIC_1', 'style': 'font-family: "c1"'}, standalone: false, }) class Dir1 {} @Directive({ selector: '[my-host-bindings-2]', host: {'class': 'HOST_STATIC_2', 'style': 'font-family: "c2"'}, standalone: false, }) class Dir2 {} TestBed.configureTestingModule({ declarations: [ // Order of directives in the template does not matter. // Order of declarations matters as it determines the relative priority for overrides. Dir1, Dir2, // Even thought component is at the end, it will still have lowest priority because // components are special that way. Cmp, ], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(getSortedClassName(div)).toEqual('HOST_STATIC_1 HOST_STATIC_2 STATIC'); // Chrome will remove quotes but Firefox and Domino do not. expect(getSortedStyle(div)).toMatch(/color: blue; font-family: "?c2"?;/); }); it('should support hostBindings inheritance', () => { @Component({ template: `<div my-host-bindings class="STATIC" style="color: blue;"></div>`, standalone: false, }) class Cmp {} @Directive({ host: {'class': 'SUPER_STATIC', 'style': 'font-family: "super";'}, standalone: false, }) class SuperDir {} @Directive({ selector: '[my-host-bindings]', host: {'class': 'HOST_STATIC', 'style': 'font-family: "host font"'}, standalone: false, }) class Dir extends SuperDir {} TestBed.configureTestingModule({declarations: [Cmp, Dir]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(getSortedClassName(div)).toEqual('HOST_STATIC STATIC SUPER_STATIC'); // Browsers keep the '"' around the font name, but Domino removes it some we do search and // replace. Yes we could do `replace(/"/g, '')` but that fails on android. expect(getSortedStyle(div).replace('"', '').replace('"', '')).toEqual( 'color: blue; font-family: host font;', ); }); it('should apply style properties that require quote wrapping', () => { @Component({ selector: 'test-style-quoting', template: ` <div style="content: &quot;foo&quot;"></div> <div style='content: "foo"'></div> <div style="content: 'foo'"></div> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const divElements = fixture.nativeElement.querySelectorAll('div'); expect(getSortedStyle(divElements[0])).toBe('content: "foo";'); expect(getSortedStyle(divElements[1])).toBe('content: "foo";'); expect(getSortedStyle(divElements[2])).toMatch(/content: ["']foo["'];/); }); it('should apply template classes in correct order', () => { @Component({ template: ` <div class="STATIC DELETE_MAP_A DELETE_PROP_B" [class]="{foo: true, DELETE_MAP_A: false}" [class.bar]="true" [class.DELETE_PROP_B]="false"></div> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const classDiv = fixture.nativeElement.querySelector('div'); expect(getSortedClassName(classDiv)).toEqual('STATIC bar foo'); }); it('should apply template styles in correct order', () => { @Component({ template: ` <div style="width: 100px; height: 200px: color: red; background-color: yellow" [style]="{width: '110px', height: null}" [style.color]=" 'blue' " [style.height.px]="undefined"></div> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const styleDiv = fixture.nativeElement.querySelector('div'); expect(getSortedStyle(styleDiv)).toEqual( 'background-color: yellow; color: blue; width: 110px;', ); }); it('should work with ngClass/ngStyle', () => { @Component({ template: `<div [ngClass]="['dynamic']" [ngStyle]="{'font-family': 'dynamic'}"></div>`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(getSortedClassName(div)).toEqual('dynamic'); expect(getSortedStyle(div)).toEqual('font-family: dynamic;'); }); });
{ "end_byte": 8782, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_8786_16605
describe('css variables', () => { const supportsCssVariables = typeof getComputedStyle !== 'undefined' && typeof CSS !== 'undefined' && typeof CSS.supports !== 'undefined' && CSS.supports('color', 'var(--fake-var)'); it('should support css variables', () => { // This test only works in browsers which support CSS variables. if (!supportsCssVariables) { return; } @Component({ template: ` <div [style.--my-var]="'100px'"> <span style="width: var(--my-var)">CONTENT</span> </div> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const span = fixture.nativeElement.querySelector('span') as HTMLElement; expect(getComputedStyle(span).getPropertyValue('width')).toEqual('100px'); }); it('should support css variables with numbers in their name inside a host binding', () => { // This test only works in browsers which support CSS variables. if (!supportsCssVariables) { return; } @Component({ template: `<h1 style="width: var(--my-1337-var)">Hello</h1>`, standalone: false, }) class Cmp { @HostBinding('style') style = '--my-1337-var: 100px;'; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const header = fixture.nativeElement.querySelector('h1') as HTMLElement; expect(getComputedStyle(header).getPropertyValue('width')).toEqual('100px'); }); it('should support case-sensitive css variables', () => { // This test only works in browsers which support CSS variables. if (!supportsCssVariables) { return; } @Component({ template: ` <div [style.--MyVar]="'100px'"> <span style="width: var(--MyVar)">CONTENT</span> </div> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const span = fixture.nativeElement.querySelector('span') as HTMLElement; expect(getComputedStyle(span).getPropertyValue('width')).toEqual('100px'); }); }); describe('non-string class keys', () => { it('should allow null in a class array binding', () => { @Component({ template: `<div [class]="['a', null, 'c']" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('a c null extra'); }); it('should allow undefined in a class array binding', () => { @Component({ template: `<div [class]="['a', undefined, 'c']" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('a c undefined extra'); }); it('should allow zero in a class array binding', () => { @Component({ template: `<div [class]="['a', 0, 'c']" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('0 a c extra'); }); it('should allow false in a class array binding', () => { @Component({ template: `<div [class]="['a', false, 'c']" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('a c false extra'); }); it('should ignore an empty string in a class array binding', () => { @Component({ template: `<div [class]="['a', '', 'c']" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('a c extra'); }); it('should ignore a string containing spaces in a class array binding', () => { @Component({ template: `<div [class]="['a', 'hello there', 'c']" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('a c extra'); }); it('should ignore a string containing spaces in a class object literal binding', () => { @Component({ template: `<div [class]="{a: true, 'hello there': true, c: true}" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('a c extra'); }); it('should ignore an object literal in a class array binding', () => { @Component({ template: `<div [class]="['a', {foo: true}, 'c']" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('a c extra'); }); it('should handle a string array in a class array binding', () => { @Component({ template: `<div [class]="['a', ['foo', 'bar'], 'c']" [class.extra]="true"></div>`, standalone: true, }) class Cmp {} const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.getAttribute('class')).toBe('a c foo,bar extra'); }); }); it('should bind [class] as input to directive', () => { @Component({ template: ` <div class="s1" [class]=" 'd1' " dir-shadows-class-input></div> <div class="s2 {{'d2'}}" dir-shadows-class-input></div> `, standalone: false, }) class Cmp {} @Directive({ selector: '[dir-shadows-class-input]', standalone: false, }) class DirectiveShadowsClassInput { constructor(private elementRef: ElementRef) {} @Input('class') set klass(value: string) { this.elementRef.nativeElement.setAttribute('shadow-class', value); } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveShadowsClassInput]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const divs = fixture.nativeElement.querySelectorAll('div'); // TODO: Use destructuring once Domino supports native ES2015, or when jsdom is used. const div1 = divs[0]; const div2 = divs[1]; // Static value `class="s1"` is always written to the DOM. expect(div1.className).toEqual('s1'); expect(div1.getAttribute('shadow-class')).toEqual('s1 d1'); expect(div2.className).toEqual(''); expect(div2.getAttribute('shadow-class')).toEqual('s2 d2'); });
{ "end_byte": 16605, "start_byte": 8786, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_16609_24701
it('should not feed host classes back into shadow input', () => { @Component({ template: ` <div class="s1" dir-shadows-class-input></div> <div class="s1" [class]=" 'd1' " dir-shadows-class-input></div> `, standalone: false, }) class Cmp {} @Directive({ selector: '[dir-shadows-class-input]', host: {'class': 'DIRECTIVE'}, standalone: false, }) class DirectiveShadowsClassInput { constructor(private elementRef: ElementRef) {} @Input('class') set klass(value: string) { this.elementRef.nativeElement.setAttribute('shadow-class', value); } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveShadowsClassInput]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const divs = fixture.nativeElement.querySelectorAll('div'); // TODO: Use destructuring once Domino supports native ES2015, or when jsdom is used. const divStatic = divs[0]; const divBinding = divs[1]; expectClass(divStatic).toEqual({'DIRECTIVE': true, 's1': true}); expect(divStatic.getAttribute('shadow-class')).toEqual('s1'); expectClass(divBinding).toEqual({'DIRECTIVE': true, 's1': true}); expect(divBinding.getAttribute('shadow-class')).toEqual('s1 d1'); }); it('should not feed host style back into shadow input', () => { @Component({ template: ` <div style="width: 1px;" dir-shadows-class-input></div> <div style="width: 1px;" [style]=" 'height:1px;' " dir-shadows-class-input></div> `, standalone: false, }) class Cmp {} @Directive({ selector: '[dir-shadows-class-input]', host: {'style': 'color: red;'}, standalone: false, }) class DirectiveShadowsStyleInput { constructor(private elementRef: ElementRef) {} @Input('style') set style(value: string) { this.elementRef.nativeElement.setAttribute('shadow-style', value); } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveShadowsStyleInput]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const divs = fixture.nativeElement.querySelectorAll('div'); // TODO: Use destructuring once Domino supports native ES2015, or when jsdom is used. const divStatic = divs[0]; const divBinding = divs[1]; expectStyle(divStatic).toEqual({'color': 'red', 'width': '1px'}); expect(divStatic.getAttribute('shadow-style')).toEqual('width: 1px;'); expectStyle(divBinding).toEqual({'color': 'red', 'width': '1px'}); expect(divBinding.getAttribute('shadow-style')).toEqual('width: 1px; height:1px;'); }); it('should bind [class] as input to directive when both static and falsy dynamic values are present', () => { @Component({ template: ` <div class="s1" [class]="classBinding" dir-shadows-class-input></div> `, standalone: false, }) class Cmp { classBinding: any = undefined; } @Directive({ selector: '[dir-shadows-class-input]', standalone: false, }) class DirectiveShadowsClassInput { constructor(private elementRef: ElementRef) {} @Input('class') set klass(value: string) { this.elementRef.nativeElement.setAttribute('shadow-class', value); } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveShadowsClassInput]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.className).toEqual('s1'); expect(div.getAttribute('shadow-class')).toEqual('s1'); fixture.componentInstance.classBinding = null; fixture.detectChanges(); expect(div.className).toEqual('s1'); expect(div.getAttribute('shadow-class')).toEqual('s1'); fixture.componentInstance.classBinding = false; fixture.detectChanges(); expect(div.className).toEqual('s1'); expect(div.getAttribute('shadow-class')).toEqual('s1'); fixture.componentInstance.classBinding = {toString: () => 'd1'}; fixture.detectChanges(); expect(div.className).toEqual('s1'); expect(div.getAttribute('shadow-class')).toEqual('s1 d1'); }); it('should bind [style] as input to directive', () => { @Component({ template: ` <div style="color: red;" [style]=" 'width: 100px;' " dir-shadows-style-input></div> `, standalone: false, }) class Cmp {} @Directive({ selector: '[dir-shadows-style-input]', standalone: false, }) class DirectiveShadowsStyleInput { constructor(private elementRef: ElementRef) {} @Input('style') set style(value: string) { this.elementRef.nativeElement.setAttribute('shadow-style', value); } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveShadowsStyleInput]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.style.cssText).toEqual('color: red;'); expect(div.getAttribute('shadow-style')).toEqual('color: red; width: 100px;'); }); it('should prevent circular ExpressionChangedAfterItHasBeenCheckedError on shadow inputs', () => { @Component({ template: `<div class="s1" dir-shadows-class-input></div>`, standalone: false, }) class Cmp {} @Directive({ selector: '[dir-shadows-class-input]', standalone: false, }) class DirectiveShadowsClassInput { @Input('class') klass: string | undefined; @HostBinding('class') get hostClasses() { return `${this.klass} SUFFIX`; } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveShadowsClassInput]}); const fixture = TestBed.createComponent(Cmp); expect(() => fixture.detectChanges()).not.toThrow(); const div = fixture.nativeElement.querySelector('div'); expect(div.className).toEqual('s1 SUFFIX'); }); it('should recover from exceptions', () => { @Component({ template: ` <div [id]="maybeThrow(id)"> <span my-dir [class]="maybeThrow(klass)" [class.foo]="maybeThrow(foo)"></span> </div> `, standalone: false, }) class Cmp { id = 'throw_id'; klass: string | string[] = 'throw_klass'; foo = `throw_foo`; maybeThrow(value: any) { if (typeof value === 'string' && value.indexOf('throw') === 0) { throw new Error(value); } return value; } } let myDirHostBinding = false; @Directive({ selector: '[my-dir]', standalone: false, }) class MyDirective { @HostBinding('class.myDir') get myDir(): boolean { if (myDirHostBinding === false) { throw new Error('class.myDir'); } return myDirHostBinding; } } TestBed.configureTestingModule({declarations: [Cmp, MyDirective]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; const div = fixture.nativeElement.querySelector('div'); const span = fixture.nativeElement.querySelector('span'); expect(() => fixture.detectChanges()).toThrowError(/throw_id/); expect(div.id).toBeFalsy(); expectClass(span).toEqual({}); cmp.id = 'myId'; expect(() => fixture.detectChanges()).toThrowError(/throw_klass/); expect(div.id).toEqual('myId'); expectClass(span).toEqual({}); cmp.klass = ['BAR']; expect(() => fixture.detectChanges()).toThrowError(/throw_foo/); expect(div.id).toEqual('myId'); expectClass(span).toEqual({BAR: true}); cmp.foo = 'foo'; expect(() => fixture.detectChanges()).toThrowError(/class.myDir/); expect(div.id).toEqual('myId'); expectClass(span).toEqual({BAR: true, foo: true}); myDirHostBinding = true; fixture.detectChanges(); expect(div.id).toEqual('myId'); expectClass(span).toEqual({BAR: true, foo: true, myDir: true}); });
{ "end_byte": 24701, "start_byte": 16609, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_24705_33028
it('should render inline style and class attribute values on the element before a directive is instantiated', () => { @Component({ template: ` <div directive-expecting-styling style="width:200px" class="abc xyz"></div> `, standalone: false, }) class Cmp {} @Directive({ selector: '[directive-expecting-styling]', standalone: false, }) class DirectiveExpectingStyling { constructor(elm: ElementRef) { const native = elm.nativeElement; native.setAttribute('data-captured-width', native.style.width); native.setAttribute('data-captured-classes', native.className); } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveExpectingStyling]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expect(element.style.width).toEqual('200px'); expect(element.getAttribute('data-captured-width')).toEqual('200px'); expect(element.className.trim()).toEqual('abc xyz'); expect(element.getAttribute('data-captured-classes')).toEqual('abc xyz'); }); it('should only render the same initial styling values once before a directive runs', () => { @Component({ template: ` <div directive-expecting-styling style="width:200px" class="abc"></div> `, standalone: false, }) class Cmp {} @Directive({ selector: '[directive-expecting-styling]', standalone: false, }) class DirectiveExpectingStyling { constructor(elm: ElementRef) { const native = elm.nativeElement; native.style.width = '300px'; native.classList.remove('abc'); } } TestBed.configureTestingModule({declarations: [Cmp, DirectiveExpectingStyling]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expect(element.style.width).toEqual('300px'); expect(element.classList.contains('abc')).toBeFalsy(); }); it('should ensure that static classes are assigned to ng-container elements and picked up for content projection', () => { @Component({ template: ` <project> outer <ng-container class="inner"> inner </ng-container> </project> `, standalone: false, }) class MyApp {} @Component({ selector: 'project', template: ` <div class="outer-area"> <ng-content></ng-content> </div> <div class="inner-area"> <ng-content select=".inner"></ng-content> </div> `, standalone: false, }) class ProjectCmp {} TestBed.configureTestingModule({declarations: [MyApp, ProjectCmp]}); const fixture = TestBed.createComponent(MyApp); const element = fixture.nativeElement; fixture.detectChanges(); const inner = element.querySelector('.inner-area'); expect(inner.textContent.trim()).toEqual('inner'); const outer = element.querySelector('.outer-area'); expect(outer.textContent.trim()).toEqual('outer'); }); it('should render initial styling for repeated nodes that a component host', () => { @Component({ selector: '[comp]', template: '', standalone: false, }) class Comp {} @Component({ template: ` <ng-template ngFor [ngForOf]="items" let-item> <p comp class="a">A</p> </ng-template> `, standalone: false, }) class App { items = [1, 2, 3]; } TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.debugElement.queryAll(By.css('.a')).length).toBe(3); }); it('should do nothing for empty style bindings', () => { @Component({ template: '<div [style.color]></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe('<div></div>'); }); it('should do nothing for empty class bindings', () => { @Component({ template: '<div [class.is-open]></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe('<div></div>'); }); it('should be able to bind zero', () => { @Component({ template: '<div #div [style.opacity]="opacity"></div>', standalone: false, }) class App { @ViewChild('div') div!: ElementRef<HTMLElement>; opacity = 0; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.div.nativeElement.style.opacity).toBe('0'); }); it('should be able to bind a SafeValue to backgroundImage', () => { @Component({ template: '<div [style.backgroundImage]="image"></div>', standalone: false, }) class Cmp { image!: SafeStyle; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const sanitizer: DomSanitizer = TestBed.inject(DomSanitizer); fixture.componentInstance.image = sanitizer.bypassSecurityTrustStyle('url("#test")'); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div') as HTMLDivElement; expect(div.style.backgroundImage).toBe('url("#test")'); expectPerfCounters({ rendererSetStyle: 1, tNode: 2, }); }); it('should set !important on a single property', () => { @Component({ template: '<div [style.width]="width"></div>', standalone: false, }) class Cmp { width!: string; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.componentInstance.width = '50px !important'; fixture.detectChanges(); const html = fixture.nativeElement.innerHTML; // We have to check the `style` attribute, because `element.style.prop` doesn't include // `!important`. Use a regex, because the different renderers produce different whitespace. expect(html).toMatch(/style=["|']width:\s*50px\s*!important/); expectPerfCounters({ rendererSetStyle: 1, tNode: 2, }); }); it('should set !important that is not preceded by a space', () => { @Component({ template: '<div [style.width]="width"></div>', standalone: false, }) class Cmp { width!: string; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.componentInstance.width = '50px!important'; fixture.detectChanges(); const html = fixture.nativeElement.innerHTML; // We have to check the `style` attribute, because `element.style.prop` doesn't include // `!important`. Use a regex, because the different renderers produce different whitespace. expect(html).toMatch(/style=["|']width:\s*50px\s*!important/); expectPerfCounters({ rendererSetStyle: 1, tNode: 2, }); }); it('should set !important on a dash-case property', () => { @Component({ template: '<div [style.margin-right]="marginRight"></div>', standalone: false, }) class Cmp { marginRight!: string; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.componentInstance.marginRight = '5px !important'; fixture.detectChanges(); const html = fixture.nativeElement.innerHTML; // We have to check the `style` attribute, because `element.style.prop` doesn't include // `!important`. Use a regex, because the different renderers produce different whitespace. expect(html).toMatch(/style=["|']margin-right:\s*5px\s*!important/); expectPerfCounters({ rendererSetStyle: 1, tNode: 2, }); });
{ "end_byte": 33028, "start_byte": 24705, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_33032_39118
it('should set !important on multiple properties', () => { @Component({ template: '<div [style]="styles"></div>', standalone: false, }) class Cmp { styles!: string; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.componentInstance.styles = 'height: 25px !important; width: 50px !important;'; fixture.detectChanges(); const html = fixture.nativeElement.innerHTML; // We have to check the `style` attribute, because `element.style.prop` doesn't include // `!important`. Use a regex, because the different renderers produce different whitespace. expect(html).toMatch(/style=["|']height:\s*25px\s*!important;\s*width:\s*50px\s*!important/); expectPerfCounters({ rendererSetStyle: 2, tNode: 2, }); }); it('should set !important if some properties are !important and other are not', () => { @Component({ template: '<div [style]="styles"></div>', standalone: false, }) class Cmp { styles!: string; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.componentInstance.styles = 'height: 25px; width: 50px !important;'; fixture.detectChanges(); const html = fixture.nativeElement.innerHTML; // We have to check the `style` attribute, because `element.style.prop` doesn't include // `!important`. Use a regex, because the different renderers produce different whitespace. expect(html).toMatch(/style=["|']height:\s*25px;\s*width:\s*50px\s*!important/); expectPerfCounters({ rendererSetStyle: 2, tNode: 2, }); }); it('should not write to the native element if a directive shadows the class input', () => { // This ex is a bit contrived. In real apps, you might have a shared class that is extended // both by components with host elements and by directives on template nodes. In that case, the // host styles for the template directives should just be ignored. @Directive({ selector: 'ng-template[styleDir]', host: {'[style.display]': 'display'}, standalone: false, }) class StyleDir { display = 'block'; } @Component({ selector: 'app-comp', template: `<ng-template styleDir></ng-template>`, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp, StyleDir]}); TestBed.createComponent(MyApp).detectChanges(); }); it('should be able to bind a SafeValue to clip-path', () => { @Component({ template: '<div [style.clip-path]="path"></div>', standalone: false, }) class Cmp { path!: SafeStyle; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const sanitizer: DomSanitizer = TestBed.inject(DomSanitizer); fixture.componentInstance.path = sanitizer.bypassSecurityTrustStyle('url("#test")'); fixture.detectChanges(); const html = fixture.nativeElement.innerHTML; // Note that check the raw HTML, because (at the time of writing) the Node-based renderer // that we use to run tests doesn't support `clip-path` in `CSSStyleDeclaration`. expect(html).toMatch(/style=["|']clip-path:\s*url\(.*#test.*\)/); }); it('should support interpolations inside a class binding', () => { @Component({ template: ` <div class="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i{{nine}}j"></div> <div class="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i"></div> <div class="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h"></div> <div class="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g"></div> <div class="a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f"></div> <div class="a{{one}}b{{two}}c{{three}}d{{four}}e"></div> <div class="a{{one}}b{{two}}c{{three}}d"></div> <div class="a{{one}}b{{two}}c"></div> <div class="a{{one}}b"></div> <div class="{{one}}"></div> `, standalone: false, }) class Cmp { one = '1'; two = '2'; three = '3'; four = '4'; five = '5'; six = '6'; seven = '7'; eight = '8'; nine = '9'; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const instance = fixture.componentInstance; fixture.detectChanges(); const divs = fixture.nativeElement.querySelectorAll('div'); expect(divs[0].getAttribute('class')).toBe('a1b2c3d4e5f6g7h8i9j'); expect(divs[1].getAttribute('class')).toBe('a1b2c3d4e5f6g7h8i'); expect(divs[2].getAttribute('class')).toBe('a1b2c3d4e5f6g7h'); expect(divs[3].getAttribute('class')).toBe('a1b2c3d4e5f6g'); expect(divs[4].getAttribute('class')).toBe('a1b2c3d4e5f'); expect(divs[5].getAttribute('class')).toBe('a1b2c3d4e'); expect(divs[6].getAttribute('class')).toBe('a1b2c3d'); expect(divs[7].getAttribute('class')).toBe('a1b2c'); expect(divs[8].getAttribute('class')).toBe('a1b'); expect(divs[9].getAttribute('class')).toBe('1'); instance.one = instance.two = instance.three = instance.four = instance.five = instance.six = instance.seven = instance.eight = instance.nine = ''; fixture.detectChanges(); expect(divs[0].getAttribute('class')).toBe('abcdefghij'); expect(divs[1].getAttribute('class')).toBe('abcdefghi'); expect(divs[2].getAttribute('class')).toBe('abcdefgh'); expect(divs[3].getAttribute('class')).toBe('abcdefg'); expect(divs[4].getAttribute('class')).toBe('abcdef'); expect(divs[5].getAttribute('class')).toBe('abcde'); expect(divs[6].getAttribute('class')).toBe('abcd'); expect(divs[7].getAttribute('class')).toBe('abc'); expect(divs[8].getAttribute('class')).toBe('ab'); expect(divs[9].getAttribute('class')).toBeFalsy(); });
{ "end_byte": 39118, "start_byte": 33032, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_39122_46103
it('should support interpolations inside a style binding', () => { @Component({ template: ` <div style="content: &quot;a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i{{nine}}j&quot;"></div> <div style="content: &quot;a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i&quot;"></div> <div style="content: &quot;a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h&quot;"></div> <div style="content: &quot;a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g&quot;"></div> <div style="content: &quot;a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f&quot;"></div> <div style="content: &quot;a{{one}}b{{two}}c{{three}}d{{four}}e&quot;"></div> <div style="content: &quot;a{{one}}b{{two}}c{{three}}d&quot;"></div> <div style="content: &quot;a{{one}}b{{two}}c&quot;"></div> <div style="content: &quot;a{{one}}b&quot;"></div> <div style="{{self}}"></div> `, standalone: false, }) class Cmp { self = 'content: "self"'; one = '1'; two = '2'; three = '3'; four = '4'; five = '5'; six = '6'; seven = '7'; eight = '8'; nine = '9'; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const instance = fixture.componentInstance; fixture.detectChanges(); const divs = fixture.nativeElement.querySelectorAll('div'); expect(divs[0].style.getPropertyValue('content')).toBe('"a1b2c3d4e5f6g7h8i9j"'); expect(divs[1].style.getPropertyValue('content')).toBe('"a1b2c3d4e5f6g7h8i"'); expect(divs[2].style.getPropertyValue('content')).toBe('"a1b2c3d4e5f6g7h"'); expect(divs[3].style.getPropertyValue('content')).toBe('"a1b2c3d4e5f6g"'); expect(divs[4].style.getPropertyValue('content')).toBe('"a1b2c3d4e5f"'); expect(divs[5].style.getPropertyValue('content')).toBe('"a1b2c3d4e"'); expect(divs[6].style.getPropertyValue('content')).toBe('"a1b2c3d"'); expect(divs[7].style.getPropertyValue('content')).toBe('"a1b2c"'); expect(divs[8].style.getPropertyValue('content')).toBe('"a1b"'); expect(divs[9].style.getPropertyValue('content')).toBe('"self"'); instance.one = instance.two = instance.three = instance.four = instance.five = instance.six = instance.seven = instance.eight = instance.nine = instance.self = ''; fixture.detectChanges(); expect(divs[0].style.getPropertyValue('content')).toBe('"abcdefghij"'); expect(divs[1].style.getPropertyValue('content')).toBe('"abcdefghi"'); expect(divs[2].style.getPropertyValue('content')).toBe('"abcdefgh"'); expect(divs[3].style.getPropertyValue('content')).toBe('"abcdefg"'); expect(divs[4].style.getPropertyValue('content')).toBe('"abcdef"'); expect(divs[5].style.getPropertyValue('content')).toBe('"abcde"'); expect(divs[6].style.getPropertyValue('content')).toBe('"abcd"'); expect(divs[7].style.getPropertyValue('content')).toBe('"abc"'); expect(divs[8].style.getPropertyValue('content')).toBe('"ab"'); expect(divs[9].style.getPropertyValue('content')).toBeFalsy(); }); it('should support interpolations inside a class binding when other classes are present', () => { @Component({ template: '<div class="zero i-{{one}} {{two}} three"></div>', standalone: false, }) class Cmp { one = 'one'; two = 'two'; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const classList = fixture.nativeElement.querySelector('div').classList; expect(classList).toContain('zero'); expect(classList).toContain('i-one'); expect(classList).toContain('two'); expect(classList).toContain('three'); fixture.componentInstance.one = fixture.componentInstance.two = ''; fixture.detectChanges(); expect(classList).toContain('zero'); expect(classList).toContain('i-'); expect(classList).toContain('three'); expect(classList).not.toContain('i-one'); expect(classList).not.toContain('two'); }); it('should support interpolations inside a style property binding', () => { @Component({ template: ` <div style.font-family="f{{one}}{{two}}{{three}}{{four}}{{five}}{{six}}{{seven}}{{eight}}{{nine}}"></div> <div style.font-family="f{{one}}{{two}}{{three}}{{four}}{{five}}{{six}}{{seven}}{{eight}}"></div> <div style.font-family="f{{one}}{{two}}{{three}}{{four}}{{five}}{{six}}{{seven}}"></div> <div style.font-family="f{{one}}{{two}}{{three}}{{four}}{{five}}{{six}}"></div> <div style.font-family="f{{one}}{{two}}{{three}}{{four}}{{five}}"></div> <div style.font-family="f{{one}}{{two}}{{three}}{{four}}"></div> <div style.font-family="f{{one}}{{two}}{{three}}"></div> <div style.font-family="f{{one}}{{two}}"></div> <div style.font-family="f{{one}}"></div> <div style.width="{{singleBinding}}"></div> `, standalone: false, }) class Cmp { singleBinding: string | null = '1337px'; one = 1; two = 2; three = 3; four = 4; five = 5; six = 6; seven = 7; eight = 8; nine = 9; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const instance = fixture.componentInstance; fixture.detectChanges(); const divs: NodeListOf<HTMLElement> = fixture.nativeElement.querySelectorAll('div'); expect(divs[0].style.fontFamily).toBe('f123456789'); expect(divs[1].style.fontFamily).toBe('f12345678'); expect(divs[2].style.fontFamily).toBe('f1234567'); expect(divs[3].style.fontFamily).toBe('f123456'); expect(divs[4].style.fontFamily).toBe('f12345'); expect(divs[5].style.fontFamily).toBe('f1234'); expect(divs[6].style.fontFamily).toBe('f123'); expect(divs[7].style.fontFamily).toBe('f12'); expect(divs[8].style.fontFamily).toBe('f1'); expect(divs[9].style.width).toBe('1337px'); instance.singleBinding = null; instance.one = instance.two = instance.three = instance.four = instance.five = instance.six = instance.seven = instance.eight = instance.nine = 1; fixture.detectChanges(); expect(divs[0].style.fontFamily).toBe('f111111111'); expect(divs[1].style.fontFamily).toBe('f11111111'); expect(divs[2].style.fontFamily).toBe('f1111111'); expect(divs[3].style.fontFamily).toBe('f111111'); expect(divs[4].style.fontFamily).toBe('f11111'); expect(divs[5].style.fontFamily).toBe('f1111'); expect(divs[6].style.fontFamily).toBe('f111'); expect(divs[7].style.fontFamily).toBe('f11'); expect(divs[8].style.fontFamily).toBe('f1'); expect(divs[9].style.width).toBeFalsy(); });
{ "end_byte": 46103, "start_byte": 39122, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_46107_52563
it('should support interpolations when a style property has a unit suffix', () => { @Component({ template: '<div style.width.px="{{one}}{{three}}{{three}}7"></div>', standalone: false, }) class Cmp { one = 1; three = 3; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.style.width).toBe('1337px'); fixture.componentInstance.one = 2; fixture.componentInstance.three = 6; fixture.detectChanges(); expect(div.style.width).toBe('2667px'); }); it('should not write to a `class` input binding in the event that there is no static class value', () => { let capturedClassBindingCount = 0; let capturedClassBindingValue: string | null | undefined = undefined; let capturedMyClassBindingCount = 0; let capturedMyClassBindingValue: string | null | undefined = undefined; @Component({ template: '<div [class]="c" [my-class-dir]="x"></div>', standalone: false, }) class Cmp { c: any = null; x = 'foo'; } @Directive({ selector: '[my-class-dir]', standalone: false, }) class MyClassDir { @Input('class') set classVal(v: string) { capturedClassBindingCount++; capturedClassBindingValue = v; } @Input('my-class-dir') set myClassVal(v: string) { capturedMyClassBindingCount++; capturedMyClassBindingValue = v; } } TestBed.configureTestingModule({declarations: [Cmp, MyClassDir]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(1); expect(capturedClassBindingValue as any).toEqual(null); expect(capturedMyClassBindingCount).toEqual(1); expect(capturedMyClassBindingValue!).toEqual('foo'); fixture.componentInstance.c = 'dynamic-value'; fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(2); expect(capturedClassBindingValue!).toEqual('dynamic-value'); expect(capturedMyClassBindingCount).toEqual(1); expect(capturedMyClassBindingValue!).toEqual('foo'); fixture.componentInstance.c = null; fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(3); expect(capturedClassBindingValue as any).toEqual(null); expect(capturedMyClassBindingCount).toEqual(1); expect(capturedMyClassBindingValue!).toEqual('foo'); fixture.componentInstance.c = ''; fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(4); expect(capturedClassBindingValue as any).toEqual(''); expect(capturedMyClassBindingCount).toEqual(1); expect(capturedMyClassBindingValue!).toEqual('foo'); }); it('should write to [class] binding during `update` mode if there is an instantiation-level value', () => { let capturedClassBindingCount = 0; let capturedClassBindingValue: string | null | undefined = undefined; @Component({ template: '<div [class]="c" my-class-dir></div>', standalone: false, }) class Cmp { c: any = 'bar'; } @Directive({ selector: '[my-class-dir]', standalone: false, }) class MyClassDir { @Input('class') set classVal(v: string) { capturedClassBindingCount++; capturedClassBindingValue = v; } } TestBed.configureTestingModule({declarations: [Cmp, MyClassDir]}); const fixture = TestBed.createComponent(Cmp); expect(capturedClassBindingCount).toEqual(0); fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(1); expect(capturedClassBindingValue as any).toEqual('bar'); fixture.componentInstance.c = 'dynamic-bar'; fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(2); expect(capturedClassBindingValue!).toEqual('dynamic-bar'); }); it('should write to a `class` input binding if there is a static class value', () => { let capturedClassBindingCount = 0; let capturedClassBindingValue: string | null = null; let capturedMyClassBindingCount = 0; let capturedMyClassBindingValue: string | null = null; @Component({ template: '<div class="static-val" [my-class-dir]="x"></div>', standalone: false, }) class Cmp { x = 'foo'; } @Directive({ selector: '[my-class-dir]', standalone: false, }) class MyClassDir { @Input('class') set classVal(v: string) { capturedClassBindingCount++; capturedClassBindingValue = v; } @Input('my-class-dir') set myClassVal(v: string) { capturedMyClassBindingCount++; capturedMyClassBindingValue = v; } } TestBed.configureTestingModule({declarations: [Cmp, MyClassDir]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(capturedClassBindingValue!).toEqual('static-val'); expect(capturedClassBindingCount).toEqual(1); expect(capturedMyClassBindingValue!).toEqual('foo'); expect(capturedMyClassBindingCount).toEqual(1); }); it('should write to a `className` input binding', () => { @Component({ selector: 'comp', template: `{{className}}`, standalone: false, }) class Comp { @Input() className: string = ''; } @Component({ template: `<comp [className]="'my-className'"></comp>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [Comp, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.firstChild.innerHTML).toBe('my-className'); }); it('should write combined class attribute and class binding to the class input', () => { @Component({ selector: 'comp', template: `{{className}}`, standalone: false, }) class Comp { @Input('class') className: string = ''; } @Component({ template: `<comp class="static" [class]="'my-className'"></comp>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [Comp, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.firstChild.innerHTML).toBe('static my-className'); });
{ "end_byte": 52563, "start_byte": 46107, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_52567_61391
it('should write to a `class` input binding if there is a static class value and there is a binding value', () => { let capturedClassBindingCount = 0; let capturedClassBindingValue: string | null = null; let capturedMyClassBindingCount = 0; let capturedMyClassBindingValue: string | null = null; @Component({ template: '<div class="static-val" [class]="c" [my-class-dir]="x"></div>', standalone: false, }) class Cmp { c: any = null; x: any = 'foo'; } @Directive({ selector: '[my-class-dir]', standalone: false, }) class MyClassDir { @Input('class') set classVal(v: string) { capturedClassBindingCount++; capturedClassBindingValue = v; } @Input('my-class-dir') set myClassVal(v: string) { capturedMyClassBindingCount++; capturedMyClassBindingValue = v; } } TestBed.configureTestingModule({declarations: [Cmp, MyClassDir]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(capturedClassBindingCount).toEqual( 2, // '2' is not ideal as '1' would be preferred. // The reason for two writes is that one is for the static // `class="static-val"` and one for `[class]="c"`. This means that // `class="static-val"` is written during the create block which is not ideal. // To do this correctly we would have to delay the `class="static-val"` until // the update block, but that would be expensive since it would require that we // would check if we possibly have this situation on every `advance()` // instruction. We don't think this is worth it, and we are just going to live // with this. ); expect(capturedClassBindingValue!).toEqual('static-val'); expect(capturedMyClassBindingCount).toEqual(1); expect(capturedMyClassBindingValue!).toEqual('foo'); capturedClassBindingCount = 0; fixture.componentInstance.c = 'dynamic-val'; fixture.detectChanges(); expect(capturedClassBindingCount).toEqual(1); expect(capturedClassBindingValue!).toEqual('static-val dynamic-val'); expect(capturedMyClassBindingCount).toEqual(1); expect(capturedMyClassBindingValue!).toEqual('foo'); }); it('should allow multiple directives to set dynamic and static classes independent of one another', () => { @Component({ template: ` <div dir-one dir-two></div> `, standalone: false, }) class Cmp {} @Directive({ selector: '[dir-one]', host: {'[class.dir-one]': 'dirOneExp'}, standalone: false, }) class DirOne { dirOneExp = true; } @Directive({ selector: '[dir-two]', host: {'class': 'dir-two'}, standalone: false, }) class DirTwo {} TestBed.configureTestingModule({declarations: [Cmp, DirOne, DirTwo]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expect(element.classList.contains('dir-one')).toBeTruthy(); expect(element.classList.contains('dir-two')).toBeTruthy(); }); it('should not write empty style values to the DOM', () => { @Component({ template: ` <div [style.color]="null" [style.--bg-color]="undefined" [style.margin]="''" [style.font-size]="' '"></div> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe('<div></div>'); }); describe('NgClass', () => { // We had a bug where NgClass would not allocate sufficient slots for host bindings, // so it would overwrite information about other directives nearby. This test checks // that TestDir's injector is not overwritten by NgClass, so TestDir should still // be found by DI when ChildDir is instantiated. it('should not overwrite other directive info when using NgClass', () => { @Directive({ selector: '[test-dir]', standalone: false, }) class TestDir {} @Directive({ selector: '[child-dir]', standalone: false, }) class ChildDir { constructor(public parent: TestDir) {} } @Component({ selector: 'app', template: ` <div class="my-class" [ngClass]="classMap" test-dir> <div *ngIf="showing" child-dir>Hello</div> </div> `, standalone: false, }) class AppComponent { classMap = {'with-button': true}; showing = false; } TestBed.configureTestingModule({declarations: [AppComponent, TestDir, ChildDir]}); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const testDirDiv = fixture.debugElement.nativeElement.querySelector('div'); expect(testDirDiv.classList).toContain('with-button'); expect(fixture.debugElement.nativeElement.textContent).not.toContain('Hello'); fixture.componentInstance.classMap = {'with-button': false}; fixture.componentInstance.showing = true; fixture.detectChanges(); const childDir = fixture.debugElement.query(By.directive(ChildDir)).injector.get(ChildDir); expect(childDir.parent).toBeInstanceOf(TestDir); expect(testDirDiv.classList).not.toContain('with-button'); expect(fixture.debugElement.nativeElement.textContent).toContain('Hello'); }); }); it('should be able to name inputs starting with `class` or `style`', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('classesInSchool') classes = ''; @Input('styleOfClothing') style = ''; } @Component({ template: '<span dir [classesInSchool]="classes" [styleOfClothing]="style"></span>', standalone: false, }) class App { @ViewChild(Dir) dir!: Dir; classes = 'math'; style = '80s'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const directive = fixture.componentInstance.dir; expect(directive.classes).toBe('math'); expect(directive.style).toBe('80s'); }); it('should be able to bind to `className`', () => { @Component({ template: '', standalone: false, }) class App { @HostBinding('className') klass = 'one two'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const classList = fixture.nativeElement.classList; expect(classList.contains('one')).toBe(true); expect(classList.contains('two')).toBe(true); }); it('should apply single property styles/classes to the element and default to any static styling values', () => { @Component({ template: ` <div [style.width]="w" [style.height]="h" [style.opacity]="o" style="width:200px; height:200px;" [class.abc]="abc" [class.xyz]="xyz"></div> `, standalone: false, }) class Cmp { w: string | null | undefined = '100px'; h: string | null | undefined = '100px'; o: string | null | undefined = '0.5'; abc = true; xyz = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expect(element.style.width).toEqual('100px'); expect(element.style.height).toEqual('100px'); expect(element.style.opacity).toEqual('0.5'); expect(element.classList.contains('abc')).toBeTruthy(); expect(element.classList.contains('xyz')).toBeFalsy(); fixture.componentInstance.w = undefined; fixture.componentInstance.h = undefined; fixture.componentInstance.o = undefined; fixture.componentInstance.abc = false; fixture.componentInstance.xyz = true; fixture.detectChanges(); expect(element.style.width).toEqual('200px'); expect(element.style.height).toEqual('200px'); expect(element.style.opacity).toBeFalsy(); expect(element.classList.contains('abc')).toBeFalsy(); expect(element.classList.contains('xyz')).toBeTruthy(); fixture.componentInstance.w = null; fixture.componentInstance.h = null; fixture.componentInstance.o = null; fixture.detectChanges(); expect(element.style.width).toBeFalsy(); expect(element.style.height).toBeFalsy(); expect(element.style.opacity).toBeFalsy(); });
{ "end_byte": 61391, "start_byte": 52567, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_61395_69130
it('should apply single style/class across the template and directive host bindings', () => { @Directive({ selector: '[dir-that-sets-width]', standalone: false, }) class DirThatSetsWidthDirective { @Input('dir-that-sets-width') @HostBinding('style.width') public width: string = ''; } @Directive({ selector: '[another-dir-that-sets-width]', host: {'[style.width]': 'width'}, standalone: false, }) class AnotherDirThatSetsWidthDirective { @Input('another-dir-that-sets-width') public width: string = ''; } @Component({ template: ` <div [style.width]="w0" [dir-that-sets-width]="w1" [another-dir-that-sets-width]="w2"> `, standalone: false, }) class Cmp { w0: string | null | undefined = null; w1: string | null | undefined = null; w2: string | null | undefined = null; } TestBed.configureTestingModule({ declarations: [Cmp, DirThatSetsWidthDirective, AnotherDirThatSetsWidthDirective], }); const fixture = TestBed.createComponent(Cmp); fixture.componentInstance.w0 = '100px'; fixture.componentInstance.w1 = '200px'; fixture.componentInstance.w2 = '300px'; fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expect(element.style.width).toEqual('100px'); fixture.componentInstance.w0 = undefined; fixture.detectChanges(); expect(element.style.width).toEqual('300px'); fixture.componentInstance.w2 = undefined; fixture.detectChanges(); expect(element.style.width).toEqual('200px'); fixture.componentInstance.w1 = undefined; fixture.detectChanges(); expect(element.style.width).toBeFalsy(); fixture.componentInstance.w2 = '400px'; fixture.detectChanges(); expect(element.style.width).toEqual('400px'); fixture.componentInstance.w1 = '500px'; fixture.componentInstance.w0 = '600px'; fixture.detectChanges(); expect(element.style.width).toEqual('600px'); }); it('should only run stylingFlush once when there are no collisions between styling properties', () => { @Directive({ selector: '[dir-with-styling]', standalone: false, }) class DirWithStyling { @HostBinding('style.font-size') public fontSize = '100px'; } @Component({ selector: 'comp-with-styling', standalone: false, }) class CompWithStyling { @HostBinding('style.width') public width = '900px'; @HostBinding('style.height') public height = '900px'; } @Component({ template: ` <comp-with-styling [style.opacity]="opacity" dir-with-styling>...</comp-with-styling> `, standalone: false, }) class Cmp { opacity: string | null = '0.5'; @ViewChild(CompWithStyling, {static: true}) compWithStyling: CompWithStyling | null = null; @ViewChild(DirWithStyling, {static: true}) dirWithStyling: DirWithStyling | null = null; } TestBed.configureTestingModule({declarations: [Cmp, DirWithStyling, CompWithStyling]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const component = fixture.componentInstance; const element = fixture.nativeElement.querySelector('comp-with-styling'); expect(element.style.opacity).toEqual('0.5'); expect(element.style.width).toEqual('900px'); expect(element.style.height).toEqual('900px'); expect(element.style.fontSize).toEqual('100px'); // once for the template flush and again for the host bindings expect(ngDevMode!.rendererSetStyle).toEqual(4); ngDevModeResetPerfCounters(); component.opacity = '0.6'; component.compWithStyling!.height = '100px'; component.compWithStyling!.width = '100px'; component.dirWithStyling!.fontSize = '50px'; fixture.detectChanges(); expect(element.style.opacity).toEqual('0.6'); expect(element.style.width).toEqual('100px'); expect(element.style.height).toEqual('100px'); expect(element.style.fontSize).toEqual('50px'); // once for the template flush and again for the host bindings expect(ngDevMode!.rendererSetStyle).toEqual(4); }); it('should combine all styling across the template, directive and component host bindings', () => { @Directive({ selector: '[dir-with-styling]', standalone: false, }) class DirWithStyling { @HostBinding('style.color') public color = 'red'; @HostBinding('style.font-size') public fontSize = '100px'; @HostBinding('class.dir') public dirClass = true; } @Component({ selector: 'comp-with-styling', standalone: false, }) class CompWithStyling { @HostBinding('style.width') public width = '900px'; @HostBinding('style.height') public height = '900px'; @HostBinding('class.comp') public compClass = true; } @Component({ template: ` <comp-with-styling [style.opacity]="opacity" [style.width]="width" [class.tpl]="tplClass" dir-with-styling>...</comp-with-styling> `, standalone: false, }) class Cmp { opacity: string | null | undefined = '0.5'; width: string | null | undefined = 'auto'; tplClass = true; } TestBed.configureTestingModule({declarations: [Cmp, DirWithStyling, CompWithStyling]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('comp-with-styling'); expectStyle(element).toEqual({ 'color': 'red', 'font-size': '100px', 'height': '900px', 'opacity': '0.5', 'width': 'auto', }); expectClass(element).toEqual({ 'dir': true, 'comp': true, 'tpl': true, }); fixture.componentInstance.width = undefined; fixture.componentInstance.opacity = undefined; fixture.componentInstance.tplClass = false; fixture.detectChanges(); expectStyle(element).toEqual({ 'color': 'red', 'width': '900px', 'height': '900px', 'font-size': '100px', }); expectClass(element).toEqual({ 'dir': true, 'comp': true, }); fixture.componentInstance.width = null; fixture.componentInstance.opacity = null; fixture.detectChanges(); expectStyle(element).toEqual({'color': 'red', 'height': '900px', 'font-size': '100px'}); }); it('should properly apply styling across sub and super class directive host bindings', () => { @Directive({ selector: '[super-class-dir]', standalone: false, }) class SuperClassDirective { @HostBinding('style.width') public w1 = '100px'; } @Component({ selector: '[sub-class-dir]', standalone: false, }) class SubClassDirective extends SuperClassDirective { @HostBinding('style.width') public w2 = '200px'; } @Component({ template: ` <div sub-class-dir [style.width]="w3"></div> `, standalone: false, }) class Cmp { w3: string | null | undefined = '300px'; } TestBed.configureTestingModule({declarations: [Cmp, SuperClassDirective, SubClassDirective]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expectStyle(element).toEqual({ 'width': '300px', }); fixture.componentInstance.w3 = null; fixture.detectChanges(); expectStyle(element).toEqual({}); fixture.componentInstance.w3 = undefined; fixture.detectChanges(); expectStyle(element).toEqual({ 'width': '200px', }); });
{ "end_byte": 69130, "start_byte": 61395, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_69134_76663
it('should apply map-based style and class entries', () => { @Component({ template: '<div [style]="s" [class]="c"></div>', standalone: false, }) class Cmp { public c: {[key: string]: any} | null = null; updateClasses(classes: string) { const c = this.c || (this.c = {}); Object.keys(this.c).forEach((className) => { c[className] = false; }); classes.split(/\s+/).forEach((className) => { c[className] = true; }); } public s: {[key: string]: any} | null = null; updateStyles(prop: string, value: string | number | null) { const s = this.s || (this.s = {}); Object.assign(s, {[prop]: value}); } reset() { this.s = null; this.c = null; } } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; comp.updateStyles('width', '100px'); comp.updateStyles('height', '200px'); comp.updateClasses('abc'); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expectStyle(element).toEqual({width: '100px', height: '200px'}); expectClass(element).toEqual({abc: true}); comp.reset(); comp.updateStyles('width', '500px'); comp.updateStyles('height', null); comp.updateClasses('def'); fixture.detectChanges(); expectStyle(element).toEqual({width: '500px'}); expectClass(element).toEqual({def: true}); }); it('should resolve styling collisions across templates, directives and components for prop and map-based entries', () => { @Directive({ selector: '[dir-that-sets-styling]', standalone: false, }) class DirThatSetsStyling { @HostBinding('style') public map: any = {color: 'red', width: '777px'}; } @Component({ template: ` <div [style.width]="width" [style]="map" style="width:200px; font-size:99px" dir-that-sets-styling #dir [class.xyz]="xyz"></div> `, standalone: false, }) class Cmp { map: any = {width: '111px', opacity: '0.5'}; width: string | null | undefined = '555px'; @ViewChild('dir', {read: DirThatSetsStyling, static: true}) dir!: DirThatSetsStyling; } TestBed.configureTestingModule({declarations: [Cmp, DirThatSetsStyling]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expectStyle(element).toEqual({ 'width': '555px', 'color': 'red', 'font-size': '99px', 'opacity': '0.5', }); comp.width = undefined; fixture.detectChanges(); expectStyle(element).toEqual({ 'width': '111px', 'color': 'red', 'font-size': '99px', 'opacity': '0.5', }); comp.map = null; fixture.detectChanges(); expectStyle(element).toEqual({ 'width': '200px', 'color': 'red', 'font-size': '99px', }); comp.dir.map = null; fixture.detectChanges(); expectStyle(element).toEqual({ 'width': '200px', 'font-size': '99px', }); }); it('should only apply each styling property once per CD across templates, components, directives', () => { @Directive({ selector: '[dir-that-sets-styling]', host: {'style': 'width:0px; height:0px'}, standalone: false, }) class DirThatSetsStyling { @HostBinding('style') public map: any = {width: '999px', height: '999px'}; } @Component({ template: ` <div #dir [style.width]="width" [style.height]="height" [style]="map" dir-that-sets-styling></div> `, standalone: false, }) class Cmp { width: string | null | undefined = '111px'; height: string | null | undefined = '111px'; map: any = {width: '555px', height: '555px'}; @ViewChild('dir', {read: DirThatSetsStyling, static: true}) dir!: DirThatSetsStyling; } TestBed.configureTestingModule({declarations: [Cmp, DirThatSetsStyling]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; ngDevModeResetPerfCounters(); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); assertStyleCounters(4, 0); assertStyle(element, 'width', '111px'); assertStyle(element, 'height', '111px'); comp.width = '222px'; ngDevModeResetPerfCounters(); fixture.detectChanges(); assertStyleCounters(1, 0); assertStyle(element, 'width', '222px'); assertStyle(element, 'height', '111px'); comp.height = '222px'; ngDevModeResetPerfCounters(); fixture.detectChanges(); assertStyleCounters(1, 0); assertStyle(element, 'width', '222px'); assertStyle(element, 'height', '222px'); comp.width = undefined; ngDevModeResetPerfCounters(); fixture.detectChanges(); assertStyleCounters(1, 0); assertStyle(element, 'width', '555px'); assertStyle(element, 'height', '222px'); comp.width = '123px'; comp.height = '123px'; ngDevModeResetPerfCounters(); fixture.detectChanges(); assertStyle(element, 'width', '123px'); assertStyle(element, 'height', '123px'); comp.map = {}; ngDevModeResetPerfCounters(); fixture.detectChanges(); // No change, hence no write assertStyleCounters(0, 0); assertStyle(element, 'width', '123px'); assertStyle(element, 'height', '123px'); comp.width = undefined; ngDevModeResetPerfCounters(); fixture.detectChanges(); assertStyleCounters(1, 0); assertStyle(element, 'width', '999px'); assertStyle(element, 'height', '123px'); comp.dir.map = null; ngDevModeResetPerfCounters(); fixture.detectChanges(); // the width is only applied once assertStyleCounters(1, 0); assertStyle(element, 'width', '0px'); assertStyle(element, 'height', '123px'); comp.dir.map = {width: '1000px', height: '1100px', color: 'red'}; ngDevModeResetPerfCounters(); fixture.detectChanges(); assertStyleCounters(2, 0); assertStyle(element, 'width', '1000px'); assertStyle(element, 'height', '123px'); assertStyle(element, 'color', 'red'); comp.height = undefined; ngDevModeResetPerfCounters(); fixture.detectChanges(); // height gets applied twice and all other // values get applied assertStyleCounters(1, 0); assertStyle(element, 'width', '1000px'); assertStyle(element, 'height', '1100px'); assertStyle(element, 'color', 'red'); comp.map = {color: 'blue', width: '2000px', opacity: '0.5'}; ngDevModeResetPerfCounters(); fixture.detectChanges(); assertStyleCounters(3, 0); assertStyle(element, 'width', '2000px'); assertStyle(element, 'height', '1100px'); assertStyle(element, 'color', 'blue'); assertStyle(element, 'opacity', '0.5'); comp.map = {color: 'blue', width: '2000px'}; ngDevModeResetPerfCounters(); fixture.detectChanges(); // all four are applied because the map was altered assertStyleCounters(0, 1); assertStyle(element, 'width', '2000px'); assertStyle(element, 'height', '1100px'); assertStyle(element, 'color', 'blue'); assertStyle(element, 'opacity', ''); });
{ "end_byte": 76663, "start_byte": 69134, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_76667_85404
it('should not sanitize style values before writing them', () => { @Component({ template: ` <div [style.width]="widthExp" [style.background-image]="bgImageExp"></div> `, standalone: false, }) class Cmp { widthExp = ''; bgImageExp = ''; styleMapExp: any = {}; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); comp.bgImageExp = 'url("javascript:img")'; fixture.detectChanges(); expect(getSortedStyle(div)).toContain('javascript:img'); // Prove that bindings work. comp.widthExp = '789px'; comp.bgImageExp = bypassSanitizationTrustStyle(comp.bgImageExp) as string; fixture.detectChanges(); expect(div.style.getPropertyValue('background-image')).toEqual('url("javascript:img")'); expect(div.style.getPropertyValue('width')).toEqual('789px'); }); it('should not sanitize style values before writing them', () => { @Component({ template: ` <div [style.width]="widthExp" [style]="styleMapExp"></div> `, standalone: false, }) class Cmp { widthExp = ''; styleMapExp: {[key: string]: any} = {}; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); comp.styleMapExp['background-image'] = 'url("javascript:img")'; fixture.detectChanges(); expect(getSortedStyle(div)).not.toContain('javascript'); // Prove that bindings work. comp.widthExp = '789px'; comp.styleMapExp = { 'background-image': bypassSanitizationTrustStyle(comp.styleMapExp['background-image']), }; fixture.detectChanges(); expect(div.style.getPropertyValue('background-image')).toEqual('url("javascript:img")'); expect(div.style.getPropertyValue('width')).toEqual('789px'); }); it('should apply a unit to a style before writing it', () => { @Component({ template: ` <div [style.width.px]="widthExp" [style.height.em]="heightExp"></div> `, standalone: false, }) class Cmp { widthExp: string | number | null = ''; heightExp: string | number | null = ''; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); comp.widthExp = '200'; comp.heightExp = 10; fixture.detectChanges(); expect(getSortedStyle(div)).toEqual('height: 10em; width: 200px;'); comp.widthExp = 0; comp.heightExp = null; fixture.detectChanges(); expect(getSortedStyle(div)).toEqual('width: 0px;'); }); it('should be able to bind a SafeValue to clip-path', () => { @Component({ template: '<div [style.clip-path]="path"></div>', standalone: false, }) class Cmp { path!: SafeStyle; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const sanitizer: DomSanitizer = TestBed.inject(DomSanitizer); fixture.componentInstance.path = sanitizer.bypassSecurityTrustStyle('url("#test")'); fixture.detectChanges(); const html = fixture.nativeElement.innerHTML; // Note that check the raw HTML, because (at the time of writing) the Node-based renderer // that we use to run tests doesn't support `clip-path` in `CSSStyleDeclaration`. expect(html).toMatch(/style=["|']clip-path:\s*url\(.*#test.*\)/); }); it('should handle values wrapped into SafeValue', () => { @Component({ template: ` <!-- Verify sanitizable style prop values wrapped in SafeValue --> <div [style.background]="getBackgroundSafe()"></div> <!-- Verify regular style prop values wrapped in SafeValue --> <p [style.width]="getWidthSafe()" [style.height]="getHeightSafe()"></p> <!-- Verify regular style prop values not wrapped in SafeValue --> <span [style.color]="getColorUnsafe()"></span> `, standalone: false, }) class MyComp { constructor(private sanitizer: DomSanitizer) {} public width: string = 'calc(20%)'; public height: string = '10px'; public background: string = '1.png'; public color: string = 'red'; private getSafeStyle(value: string) { return this.sanitizer.bypassSecurityTrustStyle(value); } getBackgroundSafe() { return this.getSafeStyle(`url("/${this.background}")`); } getWidthSafe() { return this.getSafeStyle(this.width); } getHeightSafe() { return this.getSafeStyle(this.height); } getColorUnsafe() { return this.color; } } TestBed.configureTestingModule({ imports: [CommonModule], declarations: [MyComp], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const comp = fixture.componentInstance; const div = fixture.nativeElement.querySelector('div'); const p = fixture.nativeElement.querySelector('p'); const span = fixture.nativeElement.querySelector('span'); expect(div.style.background).toContain('url("/1.png")'); expect(p.style.width).toBe('calc(20%)'); expect(p.style.height).toBe('10px'); expect(span.style.color).toBe('red'); comp.background = '2.png'; comp.width = '5px'; comp.height = '100%'; comp.color = 'green'; fixture.detectChanges(); expect(div.style.background).toContain('url("/2.png")'); expect(p.style.width).toBe('5px'); expect(p.style.height).toBe('100%'); expect(span.style.color).toBe('green'); }); it('should evaluate follow-up [style] maps even if a former map is null', () => { @Directive({ selector: '[dir-with-styling]', standalone: false, }) class DirWithStyleMap { @HostBinding('style') public styleMap: any = {color: 'red'}; } @Directive({ selector: '[dir-with-styling-part2]', standalone: false, }) class DirWithStyleMapPart2 { @HostBinding('style') public styleMap: any = {width: '200px'}; } @Component({ template: ` <div #div [style]="map" dir-with-styling dir-with-styling-part2></div> `, standalone: false, }) class Cmp { map: any = null; @ViewChild('div', {read: DirWithStyleMap, static: true}) dir1!: DirWithStyleMap; @ViewChild('div', {read: DirWithStyleMapPart2, static: true}) dir2!: DirWithStyleMapPart2; } TestBed.configureTestingModule({declarations: [Cmp, DirWithStyleMap, DirWithStyleMapPart2]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expectStyle(element).toEqual({ color: 'red', width: '200px', }); }); it('should evaluate initial style/class values on a list of elements that changes', () => { @Component({ template: ` <div *ngFor="let item of items" class="initial-class item-{{ item }}"> {{ item }} </div> `, standalone: false, }) class Cmp { items = [1, 2, 3]; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; fixture.detectChanges(); function getItemElements(): HTMLElement[] { return [].slice.call(fixture.nativeElement.querySelectorAll('div')); } function getItemClasses(): string[] { return getItemElements() .map((e) => e.className) .sort() .join(' ') .split(' '); } expect(getItemElements().length).toEqual(3); expect(getItemClasses()).toEqual([ 'initial-class', 'item-1', 'initial-class', 'item-2', 'initial-class', 'item-3', ]); comp.items = [2, 4, 6, 8]; fixture.detectChanges(); expect(getItemElements().length).toEqual(4); expect(getItemClasses()).toEqual([ 'initial-class', 'item-2', 'initial-class', 'item-4', 'initial-class', 'item-6', 'initial-class', 'item-8', ]); });
{ "end_byte": 85404, "start_byte": 76667, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_85408_93962
it('should create and update multiple class bindings across multiple elements in a template', () => { @Component({ template: ` <header class="header">header</header> <div *ngFor="let item of items" class="item item-{{ item }}"> {{ item }} </div> <footer class="footer">footer</footer> `, standalone: false, }) class Cmp { items = [1, 2, 3]; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; fixture.detectChanges(); function getItemElements(): HTMLElement[] { return [].slice.call(fixture.nativeElement.querySelectorAll('div')); } function getItemClasses(): string[] { return getItemElements() .map((e) => e.className) .sort() .join(' ') .split(' '); } const header = fixture.nativeElement.querySelector('header'); expect(header.classList.contains('header')).toBeTrue(); const footer = fixture.nativeElement.querySelector('footer'); expect(footer.classList.contains('footer')).toBeTrue(); expect(getItemElements().length).toEqual(3); expect(getItemClasses()).toEqual(['item', 'item-1', 'item', 'item-2', 'item', 'item-3']); }); it('should understand multiple directives which contain initial classes', () => { @Directive({ selector: 'dir-one', standalone: false, }) class DirOne { @HostBinding('class') public className = 'dir-one'; } @Directive({ selector: 'dir-two', standalone: false, }) class DirTwo { @HostBinding('class') public className = 'dir-two'; } @Component({ template: ` <dir-one></dir-one> <div class="initial"></div> <dir-two></dir-two> `, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp, DirOne, DirTwo]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const dirOne = fixture.nativeElement.querySelector('dir-one'); const div = fixture.nativeElement.querySelector('div'); const dirTwo = fixture.nativeElement.querySelector('dir-two'); expect(dirOne.classList.contains('dir-one')).toBeTruthy(); expect(dirTwo.classList.contains('dir-two')).toBeTruthy(); expect(div.classList.contains('initial')).toBeTruthy(); }); it('should evaluate styling across the template directives when there are multiple elements/sources of styling', () => { @Directive({ selector: '[one]', standalone: false, }) class DirOne { @HostBinding('class') public className = 'dir-one'; } @Directive({ selector: '[two]', standalone: false, }) class DirTwo { @HostBinding('class') public className = 'dir-two'; } @Component({ template: ` <div class="a" [style.width.px]="w" one></div> <div class="b" [style.height.px]="h" one two></div> <div class="c" [style.color]="c" two></div> `, standalone: false, }) class Cmp { w = 100; h = 200; c = 'red'; } TestBed.configureTestingModule({declarations: [Cmp, DirOne, DirTwo]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const divA = fixture.nativeElement.querySelector('.a'); const divB = fixture.nativeElement.querySelector('.b'); const divC = fixture.nativeElement.querySelector('.c'); expect(divA.style.width).toEqual('100px'); expect(divB.style.height).toEqual('200px'); expect(divC.style.color).toEqual('red'); }); it('should evaluate styling across the template and directives within embedded views', () => { @Directive({ selector: '[some-dir-with-styling]', standalone: false, }) class SomeDirWithStyling { @HostBinding('style') public styles = { width: '200px', height: '500px', }; } @Component({ template: ` <div class="item" *ngFor="let item of items; let i = index" [style.color]="c" [style.height.px]="h * i" some-dir-with-styling> {{ item }} </div> <section [style.width.px]="w"></section> <p [style.height.px]="h"></p> `, standalone: false, }) class Cmp { items: any[] = []; c = 'red'; w = 100; h = 100; } TestBed.configureTestingModule({declarations: [Cmp, SomeDirWithStyling]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; comp.items = [1, 2, 3, 4]; fixture.detectChanges(); const items = fixture.nativeElement.querySelectorAll('.item'); expect(items.length).toEqual(4); expect(items[0].style.height).toEqual('0px'); expect(items[1].style.height).toEqual('100px'); expect(items[2].style.height).toEqual('200px'); expect(items[3].style.height).toEqual('300px'); const section = fixture.nativeElement.querySelector('section'); const p = fixture.nativeElement.querySelector('p'); expect(section.style['width']).toEqual('100px'); expect(p.style['height']).toEqual('100px'); }); it("should flush bindings even if any styling hasn't changed in a previous directive", () => { @Directive({ selector: '[one]', standalone: false, }) class DirOne { @HostBinding('style.width') w = '100px'; @HostBinding('style.opacity') o = '0.5'; } @Directive({ selector: '[two]', standalone: false, }) class DirTwo { @HostBinding('style.height') h = '200px'; @HostBinding('style.color') c = 'red'; } @Component({ template: '<div #target one two></div>', standalone: false, }) class Cmp { @ViewChild('target', {read: DirOne, static: true}) one!: DirOne; @ViewChild('target', {read: DirTwo, static: true}) two!: DirTwo; } TestBed.configureTestingModule({declarations: [Cmp, DirOne, DirTwo]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.style.opacity).toEqual('0.5'); expect(div.style.color).toEqual('red'); expect(div.style.width).toEqual('100px'); expect(div.style.height).toEqual('200px'); comp.two.h = '300px'; fixture.detectChanges(); expect(div.style.opacity).toEqual('0.5'); expect(div.style.color).toEqual('red'); expect(div.style.width).toEqual('100px'); expect(div.style.height).toEqual('300px'); }); it('should work with NO_CHANGE values if they are applied to bindings ', () => { @Component({ template: ` <div [style.width]="w" style.height="{{ h }}" [style.opacity]="o"></div> `, standalone: false, }) class Cmp { w: any = null; h: any = null; o: any = null; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; comp.w = '100px'; comp.h = '200px'; comp.o = '0.5'; fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.style.width).toEqual('100px'); expect(div.style.height).toEqual('200px'); expect(div.style.opacity).toEqual('0.5'); comp.w = '500px'; comp.o = '1'; fixture.detectChanges(); expect(div.style.width).toEqual('500px'); expect(div.style.height).toEqual('200px'); expect(div.style.opacity).toEqual('1'); }); it('should allow [ngStyle] and [ngClass] to be used together', () => { @Component({ template: ` <div [ngClass]="c" [ngStyle]="s"></div> `, standalone: false, }) class Cmp { c: any = 'foo bar'; s: any = {width: '200px'}; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.style.width).toEqual('200px'); expect(div.classList.contains('foo')).toBeTruthy(); expect(div.classList.contains('bar')).toBeTruthy(); });
{ "end_byte": 93962, "start_byte": 85408, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_93966_102388
it('should allow to reset style property value defined using ngStyle', () => { @Component({ template: ` <div [ngStyle]="s"></div> `, standalone: false, }) class Cmp { s: any = {opacity: '1'}; clearStyle(): void { this.s = null; } } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const comp = fixture.componentInstance; fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.style.opacity).toEqual('1'); comp.clearStyle(); fixture.detectChanges(); expect(div.style.opacity).toEqual(''); }); it('should allow detectChanges to be run in a property change that causes additional styling to be rendered', () => { @Component({ selector: 'child', template: ` <div [class.ready-child]="readyTpl"></div> `, standalone: false, }) class ChildCmp { readyTpl = false; @HostBinding('class.ready-host') readyHost = false; } @Component({ selector: 'parent', template: ` <div> <div #template></div> <p>{{prop}}</p> </div> `, host: { '[style.color]': 'color', }, standalone: false, }) class ParentCmp { private _prop = ''; @ViewChild('template', {read: ViewContainerRef}) vcr: ViewContainerRef = null!; private child: ComponentRef<ChildCmp> = null!; @Input() set prop(value: string) { this._prop = value; if (this.child && value === 'go') { this.child.instance.readyHost = true; this.child.instance.readyTpl = true; this.child.changeDetectorRef.detectChanges(); } } get prop() { return this._prop; } ngAfterViewInit() { this.child = this.vcr.createComponent(ChildCmp); } } @Component({ template: `<parent [prop]="prop"></parent>`, standalone: false, }) class App { prop = 'a'; } TestBed.configureTestingModule({declarations: [App, ParentCmp, ChildCmp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(false); let readyHost = fixture.nativeElement.querySelector('.ready-host'); let readyChild = fixture.nativeElement.querySelector('.ready-child'); expect(readyHost).toBeFalsy(); expect(readyChild).toBeFalsy(); fixture.componentInstance.prop = 'go'; fixture.detectChanges(false); readyHost = fixture.nativeElement.querySelector('.ready-host'); readyChild = fixture.nativeElement.querySelector('.ready-child'); expect(readyHost).toBeTruthy(); expect(readyChild).toBeTruthy(); }); it('should allow detectChanges to be run in a hook that causes additional styling to be rendered', () => { @Component({ selector: 'child', template: ` <div [class.ready-child]="readyTpl"></div> `, standalone: false, }) class ChildCmp { readyTpl = false; @HostBinding('class.ready-host') readyHost = false; } @Component({ selector: 'parent', template: ` <div> <div #template></div> <p>{{prop}}</p> </div> `, standalone: false, }) class ParentCmp { updateChild = false; @ViewChild('template', {read: ViewContainerRef}) vcr: ViewContainerRef = null!; private child: ComponentRef<ChildCmp> = null!; ngDoCheck() { if (this.updateChild) { this.child.instance.readyHost = true; this.child.instance.readyTpl = true; this.child.changeDetectorRef.detectChanges(); } } ngAfterViewInit() { this.child = this.vcr.createComponent(ChildCmp); } } @Component({ template: `<parent #parent></parent>`, standalone: false, }) class App { @ViewChild('parent', {static: true}) public parent: ParentCmp | null = null; } TestBed.configureTestingModule({declarations: [App, ParentCmp, ChildCmp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(false); let readyHost = fixture.nativeElement.querySelector('.ready-host'); let readyChild = fixture.nativeElement.querySelector('.ready-child'); expect(readyHost).toBeFalsy(); expect(readyChild).toBeFalsy(); const parent = fixture.componentInstance.parent!; parent.updateChild = true; fixture.detectChanges(false); readyHost = fixture.nativeElement.querySelector('.ready-host'); readyChild = fixture.nativeElement.querySelector('.ready-child'); expect(readyHost).toBeTruthy(); expect(readyChild).toBeTruthy(); }); it('should allow various duplicate properties to be defined in various styling maps within the template and directive styling bindings', () => { @Component({ template: ` <div [style.width]="w" [style.height]="h" [style]="s1" [dir-with-styling]="s2"> `, standalone: false, }) class Cmp { h = '100px'; w = '100px'; s1: any = {border: '10px solid black', width: '200px'}; s2: any = {border: '10px solid red', width: '300px'}; } @Directive({ selector: '[dir-with-styling]', standalone: false, }) class DirectiveExpectingStyling { @Input('dir-with-styling') @HostBinding('style') public styles: any = null; } TestBed.configureTestingModule({declarations: [Cmp, DirectiveExpectingStyling]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expect(element.style.border).toEqual('10px solid black'); expect(element.style.width).toEqual('100px'); expect(element.style.height).toEqual('100px'); fixture.componentInstance.s1 = null; fixture.detectChanges(); expect(element.style.border).toEqual('10px solid red'); expect(element.style.width).toEqual('100px'); expect(element.style.height).toEqual('100px'); }); it('should retrieve styles set via Renderer2', () => { let dirInstance: any; @Directive({ selector: '[dir]', standalone: false, }) class Dir { constructor( public elementRef: ElementRef, public renderer: Renderer2, ) { dirInstance = this; } setStyles() { const nativeEl = this.elementRef.nativeElement; this.renderer.setStyle(nativeEl, 'transform', 'translate3d(0px, 0px, 0px)'); this.renderer.addClass(nativeEl, 'my-class'); } } @Component({ template: `<div dir></div>`, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); dirInstance.setStyles(); const div = fixture.debugElement.children[0]; expect(div.styles['transform']).toMatch(/translate3d\(0px\s*,\s*0px\s*,\s*0px\)/); expect(div.classes['my-class']).toBe(true); }); it('should remove styles via Renderer2', () => { let dirInstance: any; @Directive({ selector: '[dir]', standalone: false, }) class Dir { constructor( public elementRef: ElementRef, public renderer: Renderer2, ) { dirInstance = this; } } @Component({ template: `<div dir></div>`, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Dir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const div = fixture.debugElement.children[0]; const nativeEl = dirInstance.elementRef.nativeElement; // camel case dirInstance.renderer.setStyle(nativeEl, 'backgroundColor', 'red'); expect(div.styles['backgroundColor']).toBe('red'); dirInstance.renderer.removeStyle(nativeEl, 'backgroundColor'); expect(div.styles['backgroundColor']).toBe(''); // kebab case dirInstance.renderer.setStyle(nativeEl, 'background-color', 'red'); expect(div.styles['backgroundColor']).toBe('red'); dirInstance.renderer.removeStyle(nativeEl, 'background-color'); expect(div.styles['backgroundColor']).toBe(''); });
{ "end_byte": 102388, "start_byte": 93966, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_102392_111443
it('should not set classes when falsy value is passed while a sanitizer is present', () => { @Component({ // Note that we use `background` here because it needs to be sanitized. template: ` <span class="container" [ngClass]="{disabled: isDisabled}"></span> <div [style.background]="background"></div> `, standalone: false, }) class AppComponent { isDisabled = false; background = 'orange'; } TestBed.configureTestingModule({declarations: [AppComponent]}); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const span = fixture.nativeElement.querySelector('span'); expect(span.classList).not.toContain('disabled'); // The issue we're testing for happens after the second change detection. fixture.detectChanges(); expect(span.classList).not.toContain('disabled'); }); it('should not set classes when falsy value is passed while a sanitizer from host bindings is present', () => { @Directive({ selector: '[blockStyles]', standalone: false, }) class StylesDirective { @HostBinding('style.border') border = '1px solid red'; @HostBinding('style.background') background = 'white'; } @Component({ template: `<div class="container" [ngClass]="{disabled: isDisabled}" blockStyles></div>`, standalone: false, }) class AppComponent { isDisabled = false; } TestBed.configureTestingModule({declarations: [AppComponent, StylesDirective]}); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.classList.contains('disabled')).toBe(false); // The issue we're testing for happens after the second change detection. fixture.detectChanges(); expect(div.classList.contains('disabled')).toBe(false); }); it('should throw an error if a prop-based style/class binding value is changed during checkNoChanges', () => { @Component({ template: ` <div [style.color]="color" [class.foo]="fooClass"></div> `, standalone: false, }) class Cmp { color = 'red'; fooClass = true; ngAfterViewInit() { this.color = 'blue'; this.fooClass = false; } } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); expect(() => { fixture.detectChanges(); }).toThrowError(/ExpressionChangedAfterItHasBeenCheckedError/); }); it('should throw an error if a map-based style/class binding value is changed during checkNoChanges', () => { @Component({ template: ` <div [style]="style" [class]="klass"></div> `, standalone: false, }) class Cmp { style: any = 'width: 100px'; klass: any = 'foo'; ngAfterViewInit() { this.style = 'height: 200px'; this.klass = 'bar'; } } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); expect(() => { fixture.detectChanges(); }).toThrowError(/ExpressionChangedAfterItHasBeenCheckedError/); }); it('should properly merge class interpolation with class-based directives', () => { @Component({ template: `<div class="zero {{one}}" [class.two]="true" [ngClass]="'three'"></div>`, standalone: false, }) class MyComp { one = 'one'; } const fixture = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent( MyComp, ); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain('zero'); expect(fixture.debugElement.nativeElement.innerHTML).toContain('one'); expect(fixture.debugElement.nativeElement.innerHTML).toContain('two'); expect(fixture.debugElement.nativeElement.innerHTML).toContain('three'); }); it('should allow static and bound `class` attribute, but use last occurrence', () => { @Component({ template: ` <div id="first" class="zero {{one}}" [class]="'two'"></div> <div id="second" [class]="'two'" class="zero {{one}}"></div> `, standalone: false, }) class MyComp { one = 'one'; } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const first = fixture.nativeElement.querySelector('#first').outerHTML; expect(first).not.toContain('zero'); expect(first).not.toContain('one'); expect(first).toContain('two'); const second = fixture.nativeElement.querySelector('#second').outerHTML; expect(second).toContain('zero'); expect(second).toContain('one'); expect(second).not.toContain('two'); }); it('should allow static and bound `style` attribute, but use last occurrence', () => { @Component({ template: ` <div id="first" style="margin: {{margin}}" [style]="'padding: 20px;'"></div> <div id="second" [style]="'padding: 20px;'" style="margin: {{margin}}"></div> `, standalone: false, }) class MyComp { margin = '10px'; } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const first = fixture.nativeElement.querySelector('#first').outerHTML; expect(first).not.toContain('margin'); expect(first).toContain('padding'); const second = fixture.nativeElement.querySelector('#second').outerHTML; expect(second).toContain('margin'); expect(second).not.toContain('padding'); }); it('should allow to reset style property value defined using [style.prop.px] binding', () => { @Component({ template: '<div [style.left.px]="left"></div>', standalone: false, }) class MyComp { left = ''; } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const checks = [ ['15', '15px'], [undefined, ''], [null, ''], ['', ''], ['0', '0px'], ]; const div = fixture.nativeElement.querySelector('div'); checks.forEach((check: any[]) => { const [fieldValue, expectedValue] = check; fixture.componentInstance.left = fieldValue; fixture.detectChanges(); expect(div.style.left).toBe(expectedValue); }); }); it('should retain classes added externally', () => { @Component({ template: `<div [class]="exp"></div>`, standalone: false, }) class MyComp { exp = ''; } const fixture = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent( MyComp, ); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div')!; div.className += ' abc'; expect(splitSortJoin(div.className)).toEqual('abc'); fixture.componentInstance.exp = '1 2 3'; fixture.detectChanges(); expect(splitSortJoin(div.className)).toEqual('1 2 3 abc'); fixture.componentInstance.exp = '4 5 6 7'; fixture.detectChanges(); expect(splitSortJoin(div.className)).toEqual('4 5 6 7 abc'); function splitSortJoin(s: string) { return s.split(/\s+/).sort().join(' ').trim(); } }); describe('ExpressionChangedAfterItHasBeenCheckedError', () => { it('should not throw when bound to SafeValue', () => { @Component({ template: `<div [style.background-image]="iconSafe"></div>`, standalone: false, }) class MyComp { icon = 'https://i.imgur.com/4AiXzf8.jpg'; get iconSafe() { return this.sanitizer.bypassSecurityTrustStyle(`url("${this.icon}")`); } constructor(private sanitizer: DomSanitizer) {} } const fixture = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent( MyComp, ); fixture.detectChanges(true /* Verify that check no changes does not cause an exception */); const div: HTMLElement = fixture.nativeElement.querySelector('div'); expect(div.style.getPropertyValue('background-image')).toEqual( 'url("https://i.imgur.com/4AiXzf8.jpg")', ); }); }); isBrowser && it('should process <style> tag contents extracted from template', () => { @Component({ template: ` <style> div { width: 10px; } </style> <div></div> `, styles: ['div { width: 100px; }'], standalone: false, }) class MyComp {} TestBed.configureTestingModule({ declarations: [MyComp], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); // `styles` array values are applied first, styles from <style> tags second. const div = fixture.nativeElement.querySelector('div'); expect(getComputedStyle(div).width).toBe('10px'); });
{ "end_byte": 111443, "start_byte": 102392, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_111447_118550
it('should allow multiple styling bindings to work alongside property/attribute bindings', () => { @Component({ template: ` <div dir-that-sets-styles [style]="{'font-size': '300px'}" [attr.title]="'my-title'" [attr.data-foo]="'my-foo'"> </div>`, standalone: false, }) class MyComp {} @Directive({ selector: '[dir-that-sets-styles]', standalone: false, }) class DirThatSetsStyling { @HostBinding('style.width') public w = '100px'; @HostBinding('style.height') public h = '200px'; } const fixture = TestBed.configureTestingModule({ declarations: [MyComp, DirThatSetsStyling], }).createComponent(MyComp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div')!; expect(div.style.getPropertyValue('width')).toEqual('100px'); expect(div.style.getPropertyValue('height')).toEqual('200px'); expect(div.style.getPropertyValue('font-size')).toEqual('300px'); expect(div.getAttribute('title')).toEqual('my-title'); expect(div.getAttribute('data-foo')).toEqual('my-foo'); }); it('should allow host styling on the root element with external styling', () => { @Component({ template: '...', standalone: false, }) class MyComp { @HostBinding('class') public classes = ''; } const fixture = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent( MyComp, ); fixture.detectChanges(); const root = fixture.nativeElement as HTMLElement; expect(root.className).toEqual(''); fixture.componentInstance.classes = '1 2 3'; fixture.detectChanges(); expect(root.className.split(/\s+/).sort().join(' ')).toEqual('1 2 3'); root.classList.add('0'); expect(root.className.split(/\s+/).sort().join(' ')).toEqual('0 1 2 3'); fixture.componentInstance.classes = '1 2 3 4'; fixture.detectChanges(); expect(root.className.split(/\s+/).sort().join(' ')).toEqual('0 1 2 3 4'); }); it('should apply camelCased class names', () => { @Component({ template: `<div [class]="'fooBar'" [class.barFoo]="true"></div>`, standalone: false, }) class MyComp {} TestBed.configureTestingModule({ declarations: [MyComp], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const classList = (fixture.nativeElement.querySelector('div') as HTMLDivElement).classList; expect(classList.contains('fooBar')).toBeTruthy(); expect(classList.contains('barFoo')).toBeTruthy(); }); it('should convert camelCased style property names to snake-case', () => { @Component({ template: `<div [style]="myStyles"></div>`, standalone: false, }) class MyComp { myStyles = {}; } TestBed.configureTestingModule({ declarations: [MyComp], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div') as HTMLDivElement; fixture.componentInstance.myStyles = {fontSize: '200px'}; fixture.detectChanges(); expect(div.style.getPropertyValue('font-size')).toEqual('200px'); }); it('should recover from an error thrown in styling bindings', () => { let raiseWidthError = false; @Component({ template: `<div [style.width]="myWidth" [style.height]="'200px'"></div>`, standalone: false, }) class MyComp { get myWidth() { if (raiseWidthError) { throw new Error('...'); } return '100px'; } } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); raiseWidthError = true; expect(() => fixture.detectChanges()).toThrow(); raiseWidthError = false; fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div') as HTMLDivElement; expect(div.style.getPropertyValue('width')).toEqual('100px'); expect(div.style.getPropertyValue('height')).toEqual('200px'); }); it('should prioritize host bindings for templates first, then directives and finally components', () => { @Component({ selector: 'my-comp-with-styling', template: '', standalone: false, }) class MyCompWithStyling { @HostBinding('style') myStyles: any = {width: '300px'}; @HostBinding('style.height') myHeight: any = '305px'; } @Directive({ selector: '[my-dir-with-styling]', standalone: false, }) class MyDirWithStyling { @HostBinding('style') myStyles: any = {width: '200px'}; @HostBinding('style.height') myHeight: any = '205px'; } @Component({ template: ` <my-comp-with-styling style="height:1px; width:2px" my-dir-with-styling [style.height]="myHeight" [style]="myStyles"> </my-comp-with-styling> `, standalone: false, }) class MyComp { myStyles: {width?: string} = {width: '100px'}; myHeight: string | null | undefined = '100px'; @ViewChild(MyDirWithStyling) dir!: MyDirWithStyling; @ViewChild(MyCompWithStyling) comp!: MyCompWithStyling; } TestBed.configureTestingModule({declarations: [MyComp, MyCompWithStyling, MyDirWithStyling]}); const fixture = TestBed.createComponent(MyComp); const comp = fixture.componentInstance; const elm = fixture.nativeElement.querySelector('my-comp-with-styling')!; fixture.detectChanges(); expect(elm.style.width).toEqual('100px'); expect(elm.style.height).toEqual('100px'); comp.myStyles = {}; comp.myHeight = undefined; fixture.detectChanges(); expect(elm.style.width).toEqual('2px'); expect(elm.style.height).toEqual('1px'); comp.comp.myStyles = {}; comp.comp.myHeight = undefined; fixture.detectChanges(); expect(elm.style.width).toEqual('2px'); expect(elm.style.height).toEqual('1px'); comp.dir.myStyles = {}; comp.dir.myHeight = undefined; fixture.detectChanges(); expect(elm.style.width).toEqual('2px'); expect(elm.style.height).toEqual('1px'); }); it('should prioritize directive static bindings over components', () => { @Component({ selector: 'my-comp-with-styling', host: {style: 'color: blue'}, template: '', standalone: false, }) class MyCompWithStyling {} @Directive({ selector: '[my-dir-with-styling]', host: {style: 'color: red'}, standalone: false, }) class MyDirWithStyling {} @Component({ template: `<my-comp-with-styling my-dir-with-styling></my-comp-with-styling>`, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyComp, MyCompWithStyling, MyDirWithStyling]}); const fixture = TestBed.createComponent(MyComp); const elm = fixture.nativeElement.querySelector('my-comp-with-styling')!; fixture.detectChanges(); expect(elm.style.color).toEqual('red'); });
{ "end_byte": 118550, "start_byte": 111447, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_118554_127014
it('should combine host class.foo bindings from multiple directives', () => { @Directive({ selector: '[dir-that-sets-one-two]', exportAs: 'one', standalone: false, }) class DirThatSetsOneTwo { @HostBinding('class.one') one = false; @HostBinding('class.two') two = false; } @Directive({ selector: '[dir-that-sets-three-four]', exportAs: 'two', standalone: false, }) class DirThatSetsThreeFour { @HostBinding('class.three') three = false; @HostBinding('class.four') four = false; } @Component({ template: ` <div #div1 dir-that-sets-one-two dir-that-sets-three-four></div> <div #div2 [class.zero]="zero" dir-that-sets-one-two dir-that-sets-three-four></div> `, standalone: false, }) class MyComp { @ViewChild('div1', {static: true, read: DirThatSetsOneTwo}) public dirOneA: DirThatSetsOneTwo | null = null; @ViewChild('div1', {static: true, read: DirThatSetsThreeFour}) public dirTwoA: DirThatSetsThreeFour | null = null; @ViewChild('div2', {static: true, read: DirThatSetsOneTwo}) public dirOneB: DirThatSetsOneTwo | null = null; @ViewChild('div2', {static: true, read: DirThatSetsThreeFour}) public dirTwoB: DirThatSetsThreeFour | null = null; zero = false; } TestBed.configureTestingModule({ declarations: [MyComp, DirThatSetsThreeFour, DirThatSetsOneTwo], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const divs = fixture.nativeElement.querySelectorAll('div') as HTMLDivElement[]; // TODO: Use destructuring once Domino supports native ES2015, or when jsdom is used. const div1 = divs[0]; const div2 = divs[1]; expect(div1.className).toBe(''); expect(div2.className).toBe(''); const comp = fixture.componentInstance; comp.dirOneA!.one = comp.dirOneB!.one = true; comp.dirOneA!.two = comp.dirOneB!.two = true; fixture.detectChanges(); expect(div1.classList.contains('one')).toBeTruthy(); expect(div1.classList.contains('two')).toBeTruthy(); expect(div1.classList.contains('three')).toBeFalsy(); expect(div1.classList.contains('four')).toBeFalsy(); expect(div2.classList.contains('one')).toBeTruthy(); expect(div2.classList.contains('two')).toBeTruthy(); expect(div2.classList.contains('three')).toBeFalsy(); expect(div2.classList.contains('four')).toBeFalsy(); expect(div2.classList.contains('zero')).toBeFalsy(); comp.dirTwoA!.three = comp.dirTwoB!.three = true; comp.dirTwoA!.four = comp.dirTwoB!.four = true; fixture.detectChanges(); expect(div1.classList.contains('one')).toBeTruthy(); expect(div1.classList.contains('two')).toBeTruthy(); expect(div1.classList.contains('three')).toBeTruthy(); expect(div1.classList.contains('four')).toBeTruthy(); expect(div2.classList.contains('one')).toBeTruthy(); expect(div2.classList.contains('two')).toBeTruthy(); expect(div2.classList.contains('three')).toBeTruthy(); expect(div2.classList.contains('four')).toBeTruthy(); expect(div2.classList.contains('zero')).toBeFalsy(); comp.zero = true; fixture.detectChanges(); expect(div1.classList.contains('one')).toBeTruthy(); expect(div1.classList.contains('two')).toBeTruthy(); expect(div1.classList.contains('three')).toBeTruthy(); expect(div1.classList.contains('four')).toBeTruthy(); expect(div2.classList.contains('one')).toBeTruthy(); expect(div2.classList.contains('two')).toBeTruthy(); expect(div2.classList.contains('three')).toBeTruthy(); expect(div2.classList.contains('four')).toBeTruthy(); expect(div2.classList.contains('zero')).toBeTruthy(); }); it('should combine static host classes with component "class" host attribute', () => { @Component({ selector: 'comp-with-classes', template: '', host: {'class': 'host'}, standalone: false, }) class CompWithClasses { constructor(ref: ElementRef) { ref.nativeElement.classList.add('custom'); } } @Component({ template: `<comp-with-classes class="inline" *ngFor="let item of items"></comp-with-classes>`, standalone: false, }) class MyComp { items = [1, 2, 3]; } const fixture = TestBed.configureTestingModule({ declarations: [MyComp, CompWithClasses], }).createComponent(MyComp); fixture.detectChanges(); const [one, two, three] = fixture.nativeElement.querySelectorAll( 'comp-with-classes', ) as HTMLDivElement[]; expect(one.classList.contains('custom')).toBeTruthy(); expect(one.classList.contains('inline')).toBeTruthy(); expect(one.classList.contains('host')).toBeTruthy(); expect(two.classList.contains('custom')).toBeTruthy(); expect(two.classList.contains('inline')).toBeTruthy(); expect(two.classList.contains('host')).toBeTruthy(); expect(three.classList.contains('custom')).toBeTruthy(); expect(three.classList.contains('inline')).toBeTruthy(); expect(three.classList.contains('host')).toBeTruthy(); }); it('should allow a single style host binding on an element', () => { @Component({ template: `<div single-host-style-dir></div>`, standalone: false, }) class Cmp {} @Directive({ selector: '[single-host-style-dir]', standalone: false, }) class SingleHostStyleDir { @HostBinding('style.width') width = '100px'; } TestBed.configureTestingModule({declarations: [Cmp, SingleHostStyleDir]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('div'); expect(element.style.width).toEqual('100px'); }); it('should override class bindings when a directive extends another directive', () => { @Component({ template: `<child-comp class="template"></child-comp>`, standalone: false, }) class Cmp {} @Component({ selector: 'parent-comp', host: {'class': 'parent-comp', '[class.parent-comp-active]': 'true'}, template: '...', standalone: false, }) class ParentComp {} @Component({ selector: 'child-comp', host: { 'class': 'child-comp', '[class.child-comp-active]': 'true', '[class.parent-comp]': 'false', '[class.parent-comp-active]': 'false', }, template: '...', standalone: false, }) class ChildComp extends ParentComp {} TestBed.configureTestingModule({declarations: [Cmp, ChildComp, ParentComp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const element = fixture.nativeElement.querySelector('child-comp'); expect(element.classList.contains('template')).toBeTruthy(); expect(element.classList.contains('child-comp')).toBeTruthy(); expect(element.classList.contains('child-comp-active')).toBeTruthy(); expect(element.classList.contains('parent-comp')).toBeFalsy(); expect(element.classList.contains('parent-comp-active')).toBeFalsy(); }); it('should not set inputs called class if they are not being used in the template', () => { const logs: string[] = []; @Directive({ selector: '[test]', standalone: false, }) class MyDir { @Input('class') set className(value: string) { logs.push(value); } } @Component({ // Note that we shouldn't have a `class` attribute here. template: `<div test></div>`, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyComp, MyDir]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(logs).toEqual([]); }); it('should support `styles` as a string', () => { if (!isBrowser) { return; } @Component({ template: `<span>Hello</span>`, styles: `span {font-size: 10px}`, standalone: false, }) class Cmp {} TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); const span = fixture.nativeElement.querySelector('span') as HTMLElement; expect(getComputedStyle(span).getPropertyValue('font-size')).toBe('10px'); });
{ "end_byte": 127014, "start_byte": 118554, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/styling_spec.ts_127018_131395
describe('regression', () => { it('should support sanitizer value in the [style] bindings', () => { @Component({ template: `<div [style]="style"></div>`, standalone: false, }) class HostBindingTestComponent { style: SafeStyle; constructor(private sanitizer: DomSanitizer) { this.style = this.sanitizer.bypassSecurityTrustStyle('color: white; display: block;'); } } TestBed.configureTestingModule({declarations: [HostBindingTestComponent]}); const fixture = TestBed.createComponent(HostBindingTestComponent); fixture.detectChanges(); const div: HTMLElement = fixture.nativeElement.querySelector('div'); expectStyle(div).toEqual({color: 'white', display: 'block'}); }); it('should allow lookahead binding on second pass #35118', () => { @Component({ selector: 'my-cmp', template: ``, host: { '[class.foo]': 'hostClass', }, standalone: false, }) class MyCmp { hostClass = true; } @Directive({ selector: '[host-styling]', host: { '[class]': 'hostClass', }, standalone: false, }) class HostStylingsDir { hostClass = {'bar': true}; } @Component({ template: `<my-cmp *ngFor="let i of [1,2]" host-styling></my-cmp>`, standalone: false, }) class MyApp { // When the first view in the list gets CD-ed, everything works. // When the second view gets CD-ed, the styling has already created the data structures // in the `TView`. As a result when `[class.foo]` runs it already knows that `[class]` // is a duplicate and hence it can overwrite the `[class.foo]` binding. While the // styling resolution is happening the algorithm reads the value of the `[class]` // (because it overwrites `[class.foo]`), however `[class]` has not yet executed and // therefore it does not have normalized value in its `LView`. The result is that the // assertions fails as it expects an `KeyValueArray`. } TestBed.configureTestingModule({declarations: [MyApp, MyCmp, HostStylingsDir]}); const fixture = TestBed.createComponent(MyApp); expect(() => fixture.detectChanges()).not.toThrow(); const [cmp1, cmp2] = fixture.nativeElement.querySelectorAll('my-cmp'); expectClass(cmp1).toEqual({foo: true, bar: true}); expectClass(cmp2).toEqual({foo: true, bar: true}); }); it('should not bind [class] to @Input("className")', () => { @Component({ selector: 'my-cmp', template: `className = {{className}}`, standalone: false, }) class MyCmp { @Input() className: string = 'unbound'; } @Component({ template: `<my-cmp [class]="'bound'"></my-cmp>`, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp, MyCmp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('className = unbound'); }); it('should not bind class to @Input("className")', () => { @Component({ selector: 'my-cmp', template: `className = {{className}}`, standalone: false, }) class MyCmp { @Input() className: string = 'unbound'; } @Component({ template: `<my-cmp class="bound"></my-cmp>`, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp, MyCmp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('className = unbound'); }); }); }); function assertStyleCounters(countForSet: number, countForRemove: number) { expect(ngDevMode!.rendererSetStyle).toEqual(countForSet); expect(ngDevMode!.rendererRemoveStyle).toEqual(countForRemove); } function assertStyle(element: HTMLElement, prop: string, value: any) { expect((element.style as any)[prop]).toEqual(value); } function expectStyle(element: HTMLElement) { return expect(getElementStyles(element)); } function expectClass(element: HTMLElement) { return expect(getElementClasses(element)); }
{ "end_byte": 131395, "start_byte": 127018, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/styling_spec.ts" }
angular/packages/core/test/acceptance/directive_spec.ts_0_556
/** * @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 {CommonModule} from '@angular/common'; import { Component, Directive, ElementRef, EventEmitter, Input, NgModule, OnChanges, Output, SimpleChange, SimpleChanges, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser';
{ "end_byte": 556, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/directive_spec.ts" }
angular/packages/core/test/acceptance/directive_spec.ts_558_10053
describe('directives', () => { describe('matching', () => { @Directive({ selector: 'ng-template[test]', standalone: false, }) class TestDirective { constructor(public templateRef: TemplateRef<any>) {} } @Directive({ selector: '[title]', standalone: false, }) class TitleDirective {} @Component({ selector: 'test-cmpt', template: '', standalone: false, }) class TestComponent {} it('should match directives with attribute selectors on bindings', () => { @Directive({ selector: '[test]', standalone: false, }) class TestDir { testValue: boolean | undefined; /** Setter to assert that a binding is not invoked with stringified attribute value */ @Input() set test(value: any) { // Assert that the binding is processed correctly. The property should be set // to a "false" boolean and never to the "false" string literal. this.testValue = value; if (value !== false) { fail('Should only be called with a false Boolean value, got a non-falsy value'); } } } TestBed.configureTestingModule({declarations: [TestComponent, TestDir]}); TestBed.overrideTemplate(TestComponent, `<span class="fade" [test]="false"></span>`); const fixture = TestBed.createComponent(TestComponent); const testDir = fixture.debugElement.query(By.directive(TestDir)).injector.get(TestDir); const spanEl = fixture.nativeElement.children[0]; fixture.detectChanges(); // the "test" attribute should not be reflected in the DOM as it is here only // for directive matching purposes expect(spanEl.hasAttribute('test')).toBe(false); expect(spanEl.getAttribute('class')).toBe('fade'); expect(testDir.testValue).toBe(false); }); it('should not accidentally set inputs from attributes extracted from bindings / outputs', () => { @Directive({ selector: '[test]', standalone: false, }) class TestDir { @Input() prop1: boolean | undefined; @Input() prop2: boolean | undefined; testValue: boolean | undefined; /** Setter to assert that a binding is not invoked with stringified attribute value */ @Input() set test(value: any) { // Assert that the binding is processed correctly. The property should be set // to a "false" boolean and never to the "false" string literal. this.testValue = value; if (value !== false) { fail('Should only be called with a false Boolean value, got a non-falsy value'); } } } TestBed.configureTestingModule({declarations: [TestComponent, TestDir]}); TestBed.overrideTemplate( TestComponent, `<span class="fade" [prop1]="true" [test]="false" [prop2]="true"></span>`, ); const fixture = TestBed.createComponent(TestComponent); const testDir = fixture.debugElement.query(By.directive(TestDir)).injector.get(TestDir); const spanEl = fixture.nativeElement.children[0]; fixture.detectChanges(); // the "test" attribute should not be reflected in the DOM as it is here only // for directive matching purposes expect(spanEl.hasAttribute('test')).toBe(false); expect(spanEl.hasAttribute('prop1')).toBe(false); expect(spanEl.hasAttribute('prop2')).toBe(false); expect(spanEl.getAttribute('class')).toBe('fade'); expect(testDir.testValue).toBe(false); }); it('should match directives on ng-template', () => { TestBed.configureTestingModule({declarations: [TestComponent, TestDirective]}); TestBed.overrideTemplate(TestComponent, `<ng-template test></ng-template>`); const fixture = TestBed.createComponent(TestComponent); const nodesWithDirective = fixture.debugElement.queryAllNodes(By.directive(TestDirective)); expect(nodesWithDirective.length).toBe(1); expect( nodesWithDirective[0].injector.get(TestDirective).templateRef instanceof TemplateRef, ).toBe(true); }); it('should match directives on ng-template created by * syntax', () => { TestBed.configureTestingModule({declarations: [TestComponent, TestDirective]}); TestBed.overrideTemplate(TestComponent, `<div *test></div>`); const fixture = TestBed.createComponent(TestComponent); const nodesWithDirective = fixture.debugElement.queryAllNodes(By.directive(TestDirective)); expect(nodesWithDirective.length).toBe(1); }); it('should match directives on <ng-container>', () => { @Directive({ selector: 'ng-container[directiveA]', standalone: false, }) class DirectiveA { constructor(public viewContainerRef: ViewContainerRef) {} } @Component({ selector: 'my-component', template: ` <ng-container *ngIf="visible" directiveA> <span>Some content</span> </ng-container>`, standalone: false, }) class MyComponent { visible = true; } TestBed.configureTestingModule({ declarations: [MyComponent, DirectiveA], imports: [CommonModule], }); const fixture = TestBed.createComponent(MyComponent); fixture.detectChanges(); const directiveA = fixture.debugElement.query(By.css('span')).injector.get(DirectiveA); expect(directiveA.viewContainerRef).toBeTruthy(); }); it('should match directives on i18n-annotated attributes', () => { TestBed.configureTestingModule({declarations: [TestComponent, TitleDirective]}); TestBed.overrideTemplate( TestComponent, ` <div title="My title" i18n-title="Title translation description"></div> `, ); const fixture = TestBed.createComponent(TestComponent); const nodesWithDirective = fixture.debugElement.queryAllNodes(By.directive(TitleDirective)); expect(nodesWithDirective.length).toBe(1); }); it('should match a mix of bound directives and classes', () => { TestBed.configureTestingModule({declarations: [TestComponent, TitleDirective]}); TestBed.overrideTemplate( TestComponent, ` <div class="one two" [id]="someId" [title]="title"></div> `, ); const fixture = TestBed.createComponent(TestComponent); const nodesWithDirective = fixture.debugElement.queryAllNodes(By.directive(TitleDirective)); expect(nodesWithDirective.length).toBe(1); }); it('should match classes to directive selectors without case sensitivity', () => { @Directive({ selector: '.Titledir', standalone: false, }) class TitleClassDirective {} TestBed.configureTestingModule({declarations: [TestComponent, TitleClassDirective]}); TestBed.overrideTemplate( TestComponent, ` <div class="titleDir" [id]="someId"></div> `, ); const fixture = TestBed.createComponent(TestComponent); const nodesWithDirective = fixture.debugElement.queryAllNodes( By.directive(TitleClassDirective), ); expect(nodesWithDirective.length).toBe(1); }); it('should match class selectors on ng-template', () => { @Directive({ selector: '.titleDir', standalone: false, }) class TitleClassDirective {} TestBed.configureTestingModule({declarations: [TestComponent, TitleClassDirective]}); TestBed.overrideTemplate( TestComponent, ` <ng-template class="titleDir"></ng-template> `, ); const fixture = TestBed.createComponent(TestComponent); const nodesWithDirective = fixture.debugElement.queryAllNodes( By.directive(TitleClassDirective), ); expect(nodesWithDirective.length).toBe(1); }); it('should NOT match class selectors on ng-template created by * syntax', () => { @Directive({ selector: '.titleDir', standalone: false, }) class TitleClassDirective {} @Component({ selector: 'test-cmp', template: `<div *ngIf="condition" class="titleDir"></div>`, standalone: false, }) class TestCmp { condition = false; } TestBed.configureTestingModule({declarations: [TestCmp, TitleClassDirective]}); const fixture = TestBed.createComponent(TestCmp); const initialNodesWithDirective = fixture.debugElement.queryAllNodes( By.directive(TitleClassDirective), ); expect(initialNodesWithDirective.length).toBe(0); fixture.componentInstance.condition = true; fixture.detectChanges(); const changedNodesWithDirective = fixture.debugElement.queryAllNodes( By.directive(TitleClassDirective), ); expect(changedNodesWithDirective.length).toBe(1); }); it('should NOT match classes to directive selectors', () => { TestBed.configureTestingModule({declarations: [TestComponent, TitleDirective]}); TestBed.overrideTemplate( TestComponent, ` <div class="title" [id]="someId"></div> `, ); const fixture = TestBed.createComponent(TestComponent); const nodesWithDirective = fixture.debugElement.queryAllNodes(By.directive(TitleDirective)); expect(nodesWithDirective.length).toBe(0); });
{ "end_byte": 10053, "start_byte": 558, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/directive_spec.ts" }
angular/packages/core/test/acceptance/directive_spec.ts_10059_14827
it('should match attributes to directive selectors without case sensitivity', () => { @Directive({ selector: '[title=Titledir]', standalone: false, }) class TitleAttributeDirective {} TestBed.configureTestingModule({declarations: [TestComponent, TitleAttributeDirective]}); TestBed.overrideTemplate( TestComponent, ` <div title="titleDir" [id]="someId"></div> `, ); const fixture = TestBed.createComponent(TestComponent); const nodesWithDirective = fixture.debugElement.queryAllNodes( By.directive(TitleAttributeDirective), ); expect(nodesWithDirective.length).toBe(1); }); it('should match directives with attribute selectors on outputs', () => { @Directive({ selector: '[out]', standalone: false, }) class TestDir { @Output() out = new EventEmitter(); } TestBed.configureTestingModule({declarations: [TestComponent, TestDir]}); TestBed.overrideTemplate(TestComponent, `<span class="span" (out)="someVar = true"></span>`); const fixture = TestBed.createComponent(TestComponent); const spanEl = fixture.nativeElement.children[0]; // "out" should not be part of reflected attributes expect(spanEl.hasAttribute('out')).toBe(false); expect(spanEl.getAttribute('class')).toBe('span'); expect(fixture.debugElement.query(By.directive(TestDir))).toBeTruthy(); }); it('should not match directives based on attribute bindings', () => { const calls: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class MyDir { ngOnInit() { calls.push('MyDir.ngOnInit'); } } @Component({ selector: `my-comp`, template: `<p [attr.dir]="direction"></p><p dir="rtl"></p>`, standalone: false, }) class MyComp { direction = 'auto'; } TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); // Expect only one directive to be instantiated. expect(calls).toEqual(['MyDir.ngOnInit']); }); it('should match directives on elements with namespace', () => { const calls: string[] = []; @Directive({ selector: 'svg[dir]', standalone: false, }) class MyDir { constructor(private el: ElementRef) {} ngOnInit() { calls.push(`MyDir.ngOnInit: ${this.el.nativeElement.tagName}`); } } @Component({ selector: `my-comp`, template: `<svg dir><text dir></text></svg>`, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(calls).toEqual(['MyDir.ngOnInit: svg']); }); it('should match directives on descendant elements with namespace', () => { const calls: string[] = []; @Directive({ selector: 'text[dir]', standalone: false, }) class MyDir { constructor(private el: ElementRef) {} ngOnInit() { calls.push(`MyDir.ngOnInit: ${this.el.nativeElement.tagName}`); } } @Component({ selector: `my-comp`, template: `<svg dir><text dir></text></svg>`, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyDir, MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(calls).toEqual(['MyDir.ngOnInit: text']); }); it('should match directives when the node has "class", "style" and a binding', () => { const logs: string[] = []; @Directive({ selector: '[test]', standalone: false, }) class MyDir { constructor() { logs.push('MyDir.constructor'); } @Input('test') myInput = ''; @Input('disabled') myInput2 = ''; } @Component({ // Note that below we're checking the case where the `test` attribute is after // one `class`, one `attribute` and one other binding. template: ` <div class="a" style="font-size: 10px;" [disabled]="true" [test]="test"></div> `, standalone: false, }) class MyComp { test = ''; } TestBed.configureTestingModule({declarations: [MyComp, MyDir]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(logs).toEqual(['MyDir.constructor']); }); });
{ "end_byte": 14827, "start_byte": 10059, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/directive_spec.ts" }
angular/packages/core/test/acceptance/directive_spec.ts_14831_23797
describe('inputs', () => { it('should allow directive inputs (as a prop binding) on <ng-template>', () => { let dirInstance: WithInput; @Directive({ selector: '[dir]', standalone: false, }) class WithInput { constructor() { dirInstance = this; } @Input() dir: string = ''; } @Component({ selector: 'my-app', template: '<ng-template [dir]="message"></ng-template>', standalone: false, }) class TestComp { message = 'Hello'; } TestBed.configureTestingModule({declarations: [TestComp, WithInput]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(dirInstance!.dir).toBe('Hello'); }); it('should allow directive inputs (as an interpolated prop) on <ng-template>', () => { let dirInstance: WithInput; @Directive({ selector: '[dir]', standalone: false, }) class WithInput { constructor() { dirInstance = this; } @Input() dir: string = ''; } @Component({ selector: 'my-app', template: '<ng-template dir="{{ message }}"></ng-template>', standalone: false, }) class TestComp { message = 'Hello'; } TestBed.configureTestingModule({declarations: [TestComp, WithInput]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(dirInstance!.dir).toBe('Hello'); }); it('should allow directive inputs (as an interpolated prop) on <ng-template> with structural directives', () => { let dirInstance: WithInput; @Directive({ selector: '[dir]', standalone: false, }) class WithInput { constructor() { dirInstance = this; } @Input() dir: string = ''; } @Component({ selector: 'my-app', template: '<ng-template *ngIf="true" dir="{{ message }}"></ng-template>', standalone: false, }) class TestComp { message = 'Hello'; } TestBed.configureTestingModule({declarations: [TestComp, WithInput]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(dirInstance!.dir).toBe('Hello'); }); it('should not set structural directive inputs from static element attrs', () => { const dirInstances: StructuralDir[] = []; @Directive({ selector: '[dir]', standalone: false, }) class StructuralDir { constructor() { dirInstances.push(this); } @Input() dirOf!: number[]; @Input() dirUnboundInput: any; } @Component({ template: ` <!-- Regular form of structural directive --> <div *dir="let item of items" dirUnboundInput>Some content</div> <!-- De-sugared version of the same structural directive --> <ng-template dir let-item [dirOf]="items" dirUnboundInput> <div>Some content</div> </ng-template> `, standalone: false, }) class App { items: number[] = [1, 2, 3]; } TestBed.configureTestingModule({ declarations: [App, StructuralDir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const [regularDir, desugaredDir] = dirInstances; // When directive is used as a structural one, the `dirUnboundInput` should not be treated as // an input. expect(regularDir.dirUnboundInput).toBe(undefined); // In de-sugared version the `dirUnboundInput` acts as a regular input, so it should be set // to an empty string. expect(desugaredDir.dirUnboundInput).toBe(''); }); it('should not set structural directive inputs from element bindings', () => { const dirInstances: StructuralDir[] = []; @Directive({ selector: '[dir]', standalone: false, }) class StructuralDir { constructor() { dirInstances.push(this); } @Input() dirOf!: number[]; @Input() title: any; } @Component({ template: ` <!-- Regular form of structural directive --> <div *dir="let item of items" [title]="title">Some content</div> <!-- De-sugared version of the same structural directive --> <ng-template dir let-item [dirOf]="items" [title]="title"> <div>Some content</div> </ng-template> `, standalone: false, }) class App { items: number[] = [1, 2, 3]; title: string = 'element title'; } TestBed.configureTestingModule({ declarations: [App, StructuralDir], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const [regularDir, desugaredDir] = dirInstances; // When directive is used as a structural one, the `title` should not be treated as an input. expect(regularDir.title).toBe(undefined); // In de-sugared version the `title` acts as a regular input, so it should be set. expect(desugaredDir.title).toBe('element title'); }); it('should allow directive inputs specified using the object literal syntax in @Input', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input() plainInput: number | undefined; @Input({alias: 'alias'}) aliasedInput: number | undefined; } @Component({ template: '<div dir [plainInput]="plainValue" [alias]="aliasedValue"></div>', standalone: false, }) class App { @ViewChild(Dir) dirInstance!: Dir; plainValue = 123; aliasedValue = 321; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {dirInstance, plainValue, aliasedValue} = fixture.componentInstance; expect(dirInstance.plainInput).toBe(plainValue); expect(dirInstance.aliasedInput).toBe(aliasedValue); }); it('should allow directive inputs specified using the object literal syntax in the `inputs` array', () => { @Directive({ selector: '[dir]', inputs: [{name: 'plainInput'}, {name: 'aliasedInput', alias: 'alias'}], standalone: false, }) class Dir { plainInput: number | undefined; aliasedInput: number | undefined; } @Component({ template: '<div dir [plainInput]="plainValue" [alias]="aliasedValue"></div>', standalone: false, }) class App { @ViewChild(Dir) dirInstance!: Dir; plainValue = 123; aliasedValue = 321; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {dirInstance, plainValue, aliasedValue} = fixture.componentInstance; expect(dirInstance.plainInput).toBe(plainValue); expect(dirInstance.aliasedInput).toBe(aliasedValue); }); it('should transform incoming input values', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input({transform: (value: string) => (value ? 1 : 0)}) value = -1; } @Component({ template: '<div dir [value]="assignedValue"></div>', standalone: false, }) class TestComp { @ViewChild(Dir) dir!: Dir; assignedValue = ''; } TestBed.configureTestingModule({declarations: [TestComp, Dir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(0); fixture.componentInstance.assignedValue = 'hello'; fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(1); }); it('should transform incoming input values when declared through the `inputs` array', () => { @Directive({ selector: '[dir]', inputs: [{name: 'value', transform: (value: string) => (value ? 1 : 0)}], standalone: false, }) class Dir { value = -1; } @Component({ template: '<div dir [value]="assignedValue"></div>', standalone: false, }) class TestComp { @ViewChild(Dir) dir!: Dir; assignedValue = ''; } TestBed.configureTestingModule({declarations: [TestComp, Dir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(0); fixture.componentInstance.assignedValue = 'hello'; fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(1); });
{ "end_byte": 23797, "start_byte": 14831, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/directive_spec.ts" }
angular/packages/core/test/acceptance/directive_spec.ts_23803_31850
it('should transform incoming static input values', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input({transform: (value: string) => (value ? 1 : 0)}) value = -1; } @Component({ template: '<div dir value="staticValue"></div>', standalone: false, }) class TestComp { @ViewChild(Dir) dir!: Dir; } TestBed.configureTestingModule({declarations: [TestComp, Dir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(1); }); it('should transform incoming values for aliased inputs', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input({alias: 'valueAlias', transform: (value: string) => (value ? 1 : 0)}) value = -1; } @Component({ template: '<div dir [valueAlias]="assignedValue"></div>', standalone: false, }) class TestComp { @ViewChild(Dir) dir!: Dir; assignedValue = ''; } TestBed.configureTestingModule({declarations: [TestComp, Dir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(0); fixture.componentInstance.assignedValue = 'hello'; fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(1); }); it('should transform incoming inherited input values', () => { @Directive() class Parent { @Input({transform: (value: string) => (value ? 1 : 0)}) value = -1; } @Directive({ selector: '[dir]', standalone: false, }) class Dir extends Parent {} @Component({ template: '<div dir [value]="assignedValue"></div>', standalone: false, }) class TestComp { @ViewChild(Dir) dir!: Dir; assignedValue = ''; } TestBed.configureTestingModule({declarations: [TestComp, Dir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(0); fixture.componentInstance.assignedValue = 'hello'; fixture.detectChanges(); expect(fixture.componentInstance.dir.value).toBe(1); }); it('should transform aliased inputs coming from host directives', () => { @Directive({standalone: true}) class HostDir { @Input({transform: (value: string) => (value ? 1 : 0)}) value = -1; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['value: valueAlias']}], standalone: false, }) class Dir {} @Component({ template: '<div dir [valueAlias]="assignedValue"></div>', standalone: false, }) class TestComp { @ViewChild(HostDir) hostDir!: HostDir; assignedValue = ''; } TestBed.configureTestingModule({declarations: [TestComp, Dir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.value).toBe(0); fixture.componentInstance.assignedValue = 'hello'; fixture.detectChanges(); expect(fixture.componentInstance.hostDir.value).toBe(1); }); it('should use the transformed input values in ngOnChanges', () => { const trackedChanges: SimpleChange[] = []; @Directive({ selector: '[dir]', standalone: false, }) class Dir implements OnChanges { @Input({transform: (value: string) => (value ? 1 : 0)}) value = -1; ngOnChanges(changes: SimpleChanges): void { if (changes['value']) { trackedChanges.push(changes['value']); } } } @Component({ template: '<div dir [value]="assignedValue"></div>', standalone: false, }) class TestComp { @ViewChild(Dir) dir!: Dir; assignedValue = ''; } TestBed.configureTestingModule({declarations: [TestComp, Dir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(trackedChanges).toEqual([ jasmine.objectContaining({previousValue: undefined, currentValue: 0}), ]); fixture.componentInstance.assignedValue = 'hello'; fixture.detectChanges(); expect(trackedChanges).toEqual([ jasmine.objectContaining({previousValue: undefined, currentValue: 0}), jasmine.objectContaining({previousValue: 0, currentValue: 1}), ]); }); it('should invoke the transform function with the directive instance as the context', () => { let instance: Dir | undefined; function transform(this: Dir, _value: string) { instance = this; return 0; } @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input({transform}) value: any; } @Component({ template: '<div dir value="foo"></div>', standalone: false, }) class TestComp { @ViewChild(Dir) dir!: Dir; } TestBed.configureTestingModule({declarations: [TestComp, Dir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(instance).toBe(fixture.componentInstance.dir); }); it('should transform value assigned using setInput', () => { @Component({ selector: 'comp', template: '', standalone: false, }) class Comp { @Input({transform: (value: string) => (value ? 1 : 0)}) value = -1; } @Component({ template: '<ng-container #location/>', standalone: false, }) class TestComp { @ViewChild('location', {read: ViewContainerRef}) vcr!: ViewContainerRef; } TestBed.configureTestingModule({declarations: [TestComp, Comp]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); const ref = fixture.componentInstance.vcr.createComponent(Comp); ref.setInput('value', ''); expect(ref.instance.value).toBe(0); ref.setInput('value', 'hello'); expect(ref.instance.value).toBe(1); }); }); describe('outputs', () => { @Directive({ selector: '[out]', standalone: false, }) class TestDir { @Output() out = new EventEmitter(); } it('should allow outputs of directive on ng-template', () => { @Component({ template: `<ng-template (out)="value = true"></ng-template>`, standalone: false, }) class TestComp { @ViewChild(TestDir, {static: true}) testDir: TestDir | undefined; value = false; } TestBed.configureTestingModule({declarations: [TestComp, TestDir]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(fixture.componentInstance.testDir).toBeTruthy(); expect(fixture.componentInstance.value).toBe(false); fixture.componentInstance.testDir!.out.emit(); fixture.detectChanges(); expect(fixture.componentInstance.value).toBe(true); }); it('should allow outputs of directive on ng-container', () => { @Component({ template: ` <ng-container (out)="value = true"> <span>Hello</span> </ng-container>`, standalone: false, }) class TestComp { value = false; } TestBed.configureTestingModule({declarations: [TestComp, TestDir]}); const fixture = TestBed.createComponent(TestComp); const testDir = fixture.debugElement.query(By.css('span')).injector.get(TestDir); expect(fixture.componentInstance.value).toBe(false); testDir.out.emit(); fixture.detectChanges(); expect(fixture.componentInstance.value).toBeTruthy(); }); });
{ "end_byte": 31850, "start_byte": 23803, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/directive_spec.ts" }
angular/packages/core/test/acceptance/directive_spec.ts_31854_41010
describe('attribute shadowing behaviors', () => { /** * To match ViewEngine, we need to ensure the following behaviors */ @Directive({ selector: '[dir-with-title]', standalone: false, }) class DirWithTitle { @Input() title = ''; } it('should set both the div attribute and the directive input for `title="value"`', () => { @Component({ template: `<div dir-with-title title="a"></div>`, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe('a'); expect(div.getAttribute('title')).toBe('a'); }); it('should set the directive input only, shadowing the title property of the div, for `[title]="value"`', () => { @Component({ template: `<div dir-with-title [title]="value"></div>`, standalone: false, }) class App { value = 'a'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); // We are checking the property here, not the attribute, because in the case of // [key]="value" we are always setting the property of the instance, and actually setting // the attribute is just a side-effect of the DOM implementation. expect(dirWithTitle.title).toBe('a'); expect(div.title).toBe(''); }); it('should allow setting directive `title` input with `[title]="value"` and a "attr.title" attribute with `attr.title="test"`', () => { @Component({ template: `<div dir-with-title [title]="value" attr.title="test"></div>`, standalone: false, }) class App { value = 'a'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe('a'); expect(div.getAttribute('attr.title')).toBe('test'); expect(div.title).toBe(''); }); it('should allow setting directive `title` input with `[title]="value1"` and attribute with `[attr.title]="value2"`', () => { @Component({ template: `<div dir-with-title [title]="value1" [attr.title]="value2"></div>`, standalone: false, }) class App { value1 = 'a'; value2 = 'b'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe('a'); expect(div.getAttribute('title')).toBe('b'); }); it('should allow setting directive `title` input with `[title]="value1"` and attribute with `attr.title="{{value2}}"`', () => { @Component({ template: `<div dir-with-title [title]="value1" attr.title="{{value2}}"></div>`, standalone: false, }) class App { value1 = 'a'; value2 = 'b'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe('a'); expect(div.getAttribute('title')).toBe('b'); }); it('should allow setting directive `title` input with `title="{{value}}"` and a "attr.title" attribute with `attr.title="test"`', () => { @Component({ template: `<div dir-with-title title="{{value}}" attr.title="test"></div>`, standalone: false, }) class App { value = 'a'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe('a'); expect(div.getAttribute('attr.title')).toBe('test'); expect(div.title).toBe(''); }); it('should allow setting directive `title` input with `title="{{value1}}"` and attribute with `[attr.title]="value2"`', () => { @Component({ template: `<div dir-with-title title="{{value1}}" [attr.title]="value2"></div>`, standalone: false, }) class App { value1 = 'a'; value2 = 'b'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe('a'); expect(div.getAttribute('title')).toBe('b'); }); it('should allow setting directive `title` input with `title="{{value1}}"` and attribute with `attr.title="{{value2}}"`', () => { @Component({ template: `<div dir-with-title title="{{value1}}" attr.title="{{value2}}"></div>`, standalone: false, }) class App { value1 = 'a'; value2 = 'b'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe('a'); expect(div.getAttribute('title')).toBe('b'); }); it('should set the directive input only, shadowing the title property on the div, for `title="{{value}}"`', () => { @Component({ template: `<div dir-with-title title="{{value}}"></div>`, standalone: false, }) class App { value = 'a'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe('a'); expect(div.title).toBe(''); }); it('should set the title attribute only, not directive input, for `attr.title="{{value}}"`', () => { @Component({ template: `<div dir-with-title attr.title="{{value}}"></div>`, standalone: false, }) class App { value = 'a'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe(''); expect(div.getAttribute('title')).toBe('a'); }); it('should set the title attribute only, not directive input, for `[attr.title]="value"`', () => { @Component({ template: `<div dir-with-title [attr.title]="value"></div>`, standalone: false, }) class App { value = 'a'; } TestBed.configureTestingModule({ declarations: [App, DirWithTitle], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirWithTitle = fixture.debugElement .query(By.directive(DirWithTitle)) .injector.get(DirWithTitle); const div = fixture.nativeElement.querySelector('div'); expect(dirWithTitle.title).toBe(''); expect(div.getAttribute('title')).toBe('a'); }); });
{ "end_byte": 41010, "start_byte": 31854, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/directive_spec.ts" }
angular/packages/core/test/acceptance/directive_spec.ts_41014_43747
describe('directives with the same selector', () => { it('should process Directives from `declarations` list after imported ones', () => { const log: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class DirectiveA { constructor() { log.push('DirectiveA.constructor'); } ngOnInit() { log.push('DirectiveA.ngOnInit'); } } @NgModule({ declarations: [DirectiveA], exports: [DirectiveA], }) class ModuleA {} @Directive({ selector: '[dir]', standalone: false, }) class DirectiveB { constructor() { log.push('DirectiveB.constructor'); } ngOnInit() { log.push('DirectiveB.ngOnInit'); } } @Component({ selector: 'app', template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({ imports: [ModuleA], declarations: [DirectiveB, App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(log).toEqual([ 'DirectiveA.constructor', 'DirectiveB.constructor', 'DirectiveA.ngOnInit', 'DirectiveB.ngOnInit', ]); }); it('should respect imported module order', () => { const log: string[] = []; @Directive({ selector: '[dir]', standalone: false, }) class DirectiveA { constructor() { log.push('DirectiveA.constructor'); } ngOnInit() { log.push('DirectiveA.ngOnInit'); } } @NgModule({ declarations: [DirectiveA], exports: [DirectiveA], }) class ModuleA {} @Directive({ selector: '[dir]', standalone: false, }) class DirectiveB { constructor() { log.push('DirectiveB.constructor'); } ngOnInit() { log.push('DirectiveB.ngOnInit'); } } @NgModule({ declarations: [DirectiveB], exports: [DirectiveB], }) class ModuleB {} @Component({ selector: 'app', template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({ imports: [ModuleA, ModuleB], declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(log).toEqual([ 'DirectiveA.constructor', 'DirectiveB.constructor', 'DirectiveA.ngOnInit', 'DirectiveB.ngOnInit', ]); }); }); });
{ "end_byte": 43747, "start_byte": 41014, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/directive_spec.ts" }