|
6 | 6 | * found in the LICENSE file at https://angular.io/license
|
7 | 7 | */
|
8 | 8 |
|
9 |
| -import {AfterViewChecked, AfterViewInit, Component, Directive, ElementRef, EventEmitter, forwardRef, inject, Inject, InjectionToken, Input, OnChanges, OnInit, Output, SimpleChanges, Type, ViewChild, ViewContainerRef} from '@angular/core'; |
| 9 | +import {AfterViewChecked, AfterViewInit, ChangeDetectorRef, Component, Directive, ElementRef, EventEmitter, forwardRef, inject, Inject, InjectionToken, Input, OnChanges, OnInit, Output, SimpleChanges, Type, ViewChild, ViewContainerRef} from '@angular/core'; |
10 | 10 | import {TestBed} from '@angular/core/testing';
|
11 | 11 | import {By} from '@angular/platform-browser';
|
12 | 12 |
|
@@ -919,6 +919,44 @@ describe('host directives', () => {
|
919 | 919 | expect(() => TestBed.createComponent(App))
|
920 | 920 | .toThrowError(/NG0200: Circular dependency in DI detected for HostDir/);
|
921 | 921 | });
|
| 922 | + |
| 923 | + it('should inject a valid ChangeDetectorRef when attached to a component', () => { |
| 924 | + type InternalChangeDetectorRef = ChangeDetectorRef&{_lView: unknown}; |
| 925 | + |
| 926 | + @Directive({standalone: true}) |
| 927 | + class HostDir { |
| 928 | + changeDetectorRef = inject(ChangeDetectorRef) as InternalChangeDetectorRef; |
| 929 | + } |
| 930 | + |
| 931 | + @Component({selector: 'my-comp', hostDirectives: [HostDir], template: ''}) |
| 932 | + class Comp { |
| 933 | + changeDetectorRef = inject(ChangeDetectorRef) as InternalChangeDetectorRef; |
| 934 | + } |
| 935 | + |
| 936 | + @Component({template: '<my-comp></my-comp>'}) |
| 937 | + class App { |
| 938 | + @ViewChild(HostDir) hostDir!: HostDir; |
| 939 | + @ViewChild(Comp) comp!: Comp; |
| 940 | + } |
| 941 | + |
| 942 | + TestBed.configureTestingModule({declarations: [App, Comp]}); |
| 943 | + const fixture = TestBed.createComponent(App); |
| 944 | + fixture.detectChanges(); |
| 945 | + |
| 946 | + const hostDirectiveCdr = fixture.componentInstance.hostDir.changeDetectorRef; |
| 947 | + const componentCdr = fixture.componentInstance.comp.changeDetectorRef; |
| 948 | + |
| 949 | + // We can't assert that the change detectors are the same by comparing |
| 950 | + // them directly, because a new one is created each time. Instead of we |
| 951 | + // compare that they're associated with the same LView. |
| 952 | + expect(hostDirectiveCdr._lView).toBeTruthy(); |
| 953 | + expect(componentCdr._lView).toBeTruthy(); |
| 954 | + expect(hostDirectiveCdr._lView).toBe(componentCdr._lView); |
| 955 | + expect(() => { |
| 956 | + hostDirectiveCdr.markForCheck(); |
| 957 | + hostDirectiveCdr.detectChanges(); |
| 958 | + }).not.toThrow(); |
| 959 | + }); |
922 | 960 | });
|
923 | 961 |
|
924 | 962 | describe('outputs', () => {
|
|
0 commit comments