forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
host_directives_spec.ts
3223 lines (2633 loc) · 95.1 KB
/
host_directives_spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* @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.io/license
*/
import {AfterViewChecked, AfterViewInit, ChangeDetectorRef, Component, Directive, ElementRef, EventEmitter, forwardRef, inject, Inject, InjectionToken, Input, OnChanges, OnInit, Output, SimpleChanges, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {getComponent, getDirectives} from '../../src/render3/util/discovery_utils';
describe('host directives', () => {
it('should apply a basic host directive', () => {
const logs: string[] = [];
@Directive({
standalone: true,
host: {'host-dir-attr': '', 'class': 'host-dir', 'style': 'height: 50px'}
})
class HostDir {
constructor() {
logs.push('HostDir');
}
}
@Directive({
selector: '[dir]',
host: {'host-attr': '', 'class': 'dir', 'style': 'width: 50px'},
hostDirectives: [HostDir]
})
class Dir {
constructor() {
logs.push('Dir');
}
}
@Component({template: '<div dir></div>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Dir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(logs).toEqual(['HostDir', 'Dir']);
expect(fixture.nativeElement.innerHTML)
.toBe(
'<div host-dir-attr="" host-attr="" dir="" ' +
'class="host-dir dir" style="height: 50px; width: 50px;"></div>');
});
it('should apply a host directive referenced through a forwardRef', () => {
const logs: string[] = [];
@Directive({
selector: '[dir]',
hostDirectives: [forwardRef(() => HostDir), {directive: forwardRef(() => OtherHostDir)}]
})
class Dir {
constructor() {
logs.push('Dir');
}
}
@Directive({standalone: true})
class HostDir {
constructor() {
logs.push('HostDir');
}
}
@Directive({standalone: true})
class OtherHostDir {
constructor() {
logs.push('OtherHostDir');
}
}
@Component({template: '<div dir></div>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Dir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(logs).toEqual(['HostDir', 'OtherHostDir', 'Dir']);
});
it('should apply a chain of host directives', () => {
const logs: string[] = [];
const token = new InjectionToken('message');
let diTokenValue: string;
@Directive({
host: {
'class': 'leaf',
'id': 'leaf-id',
},
providers: [{provide: token, useValue: 'leaf value'}],
standalone: true
})
class Chain1_3 {
constructor(@Inject(token) tokenValue: string) {
diTokenValue = tokenValue;
logs.push('Chain1 - level 3');
}
}
@Directive({
standalone: true,
hostDirectives: [Chain1_3],
})
class Chain1_2 {
constructor() {
logs.push('Chain1 - level 2');
}
}
@Directive({
standalone: true,
hostDirectives: [Chain1_2],
})
class Chain1 {
constructor() {
logs.push('Chain1 - level 1');
}
}
@Directive({
standalone: true,
host: {
'class': 'middle',
'id': 'middle-id',
},
providers: [{provide: token, useValue: 'middle value'}],
})
class Chain2_2 {
constructor() {
logs.push('Chain2 - level 2');
}
}
@Directive({
standalone: true,
hostDirectives: [Chain2_2],
})
class Chain2 {
constructor() {
logs.push('Chain2 - level 1');
}
}
@Directive({standalone: true})
class Chain3_2 {
constructor() {
logs.push('Chain3 - level 2');
}
}
@Directive({standalone: true, hostDirectives: [Chain3_2]})
class Chain3 {
constructor() {
logs.push('Chain3 - level 1');
}
}
@Component({
selector: 'my-comp',
host: {
'class': 'host',
'id': 'host-id',
},
template: '',
hostDirectives: [Chain1, Chain2, Chain3],
providers: [{provide: token, useValue: 'host value'}],
})
class MyComp {
constructor() {
logs.push('MyComp');
}
}
@Directive({standalone: true})
class SelectorMatchedHostDir {
constructor() {
logs.push('SelectorMatchedHostDir');
}
}
@Directive({
selector: '[selector-matched-dir]',
hostDirectives: [SelectorMatchedHostDir],
})
class SelectorMatchedDir {
constructor() {
logs.push('SelectorMatchedDir');
}
}
@Component({template: '<my-comp selector-matched-dir></my-comp>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, MyComp, SelectorMatchedDir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(diTokenValue!).toBe('host value');
expect(fixture.nativeElement.innerHTML)
.toBe('<my-comp id="host-id" selector-matched-dir="" class="leaf middle host"></my-comp>');
expect(logs).toEqual([
'Chain1 - level 3',
'Chain1 - level 2',
'Chain1 - level 1',
'Chain2 - level 2',
'Chain2 - level 1',
'Chain3 - level 2',
'Chain3 - level 1',
'MyComp',
'SelectorMatchedHostDir',
'SelectorMatchedDir',
]);
});
it('should be able to query for the host directives', () => {
let hostInstance!: Host;
let firstHostDirInstance!: FirstHostDir;
let secondHostDirInstance!: SecondHostDir;
@Directive({standalone: true})
class SecondHostDir {
constructor() {
secondHostDirInstance = this;
}
}
@Directive({standalone: true, hostDirectives: [SecondHostDir]})
class FirstHostDir {
constructor() {
firstHostDirInstance = this;
}
}
@Directive({selector: '[dir]', hostDirectives: [FirstHostDir]})
class Host {
constructor() {
hostInstance = this;
}
}
@Component({template: '<div dir></div>'})
class App {
@ViewChild(FirstHostDir) firstHost!: FirstHostDir;
@ViewChild(SecondHostDir) secondHost!: SecondHostDir;
}
TestBed.configureTestingModule({declarations: [App, Host]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(hostInstance instanceof Host).toBe(true);
expect(firstHostDirInstance instanceof FirstHostDir).toBe(true);
expect(secondHostDirInstance instanceof SecondHostDir).toBe(true);
expect(fixture.componentInstance.firstHost).toBe(firstHostDirInstance);
expect(fixture.componentInstance.secondHost).toBe(secondHostDirInstance);
});
it('should be able to reference exported host directives', () => {
@Directive({standalone: true, exportAs: 'secondHost'})
class SecondHostDir {
name = 'SecondHost';
}
@Directive({standalone: true, hostDirectives: [SecondHostDir], exportAs: 'firstHost'})
class FirstHostDir {
name = 'FirstHost';
}
@Directive({selector: '[dir]', hostDirectives: [FirstHostDir]})
class Host {
}
@Component({
template: `
<div
dir
#firstHost="firstHost"
#secondHost="secondHost">{{firstHost.name}} | {{secondHost.name}}</div>
`
})
class App {
}
TestBed.configureTestingModule({declarations: [App, Host]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('FirstHost | SecondHost');
});
describe('lifecycle hooks', () => {
it('should invoke lifecycle hooks from the host directives', () => {
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');
}
}
@Directive({selector: '[dir]', hostDirectives: [HostDir, OtherHostDir]})
class Dir implements OnInit, AfterViewInit, AfterViewChecked {
ngOnInit() {
logs.push('Dir - ngOnInit');
}
ngAfterViewInit() {
logs.push('Dir - ngAfterViewInit');
}
ngAfterViewChecked() {
logs.push('Dir - ngAfterViewChecked');
}
}
@Component({template: '<div dir></div>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Dir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(logs).toEqual([
'HostDir - ngOnInit',
'OtherHostDir - ngOnInit',
'Dir - ngOnInit',
'HostDir - ngAfterViewInit',
'HostDir - ngAfterViewChecked',
'OtherHostDir - ngAfterViewInit',
'OtherHostDir - ngAfterViewChecked',
'Dir - ngAfterViewInit',
'Dir - ngAfterViewChecked',
]);
});
// Note: lifecycle hook order is different when components and directives are mixed so this
// test aims to cover it. Usually lifecycle hooks are invoked based on the order in which
// directives were matched, but components bypass this logic and always execute first.
it('should invoke host directive lifecycle hooks before the host component hooks', () => {
const logs: string[] = [];
// Utility so we don't have to repeat the logging code.
@Directive({standalone: true})
abstract class LogsLifecycles implements OnInit, AfterViewInit {
abstract name: string;
ngOnInit() {
logs.push(`${this.name} - ngOnInit`);
}
ngAfterViewInit() {
logs.push(`${this.name} - ngAfterViewInit`);
}
}
@Directive({standalone: true})
class ChildHostDir extends LogsLifecycles {
override name = 'ChildHostDir';
}
@Directive({standalone: true})
class OtherChildHostDir extends LogsLifecycles {
override name = 'OtherChildHostDir';
}
@Component({
selector: 'child',
hostDirectives: [ChildHostDir, OtherChildHostDir],
})
class Child extends LogsLifecycles {
override name = 'Child';
}
@Directive({standalone: true})
class ParentHostDir extends LogsLifecycles {
override name = 'ParentHostDir';
}
@Directive({standalone: true})
class OtherParentHostDir extends LogsLifecycles {
override name = 'OtherParentHostDir';
}
@Component({
selector: 'parent',
hostDirectives: [ParentHostDir, OtherParentHostDir],
template: '<child plain-dir="PlainDir on child"></child>',
})
class Parent extends LogsLifecycles {
override name = 'Parent';
}
@Directive({selector: '[plain-dir]'})
class PlainDir extends LogsLifecycles {
@Input('plain-dir') override name = '';
}
@Component({template: '<parent plain-dir="PlainDir on parent"></parent>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Parent, Child, PlainDir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(logs).toEqual([
'ParentHostDir - ngOnInit',
'OtherParentHostDir - ngOnInit',
'Parent - ngOnInit',
'PlainDir on parent - ngOnInit',
'ChildHostDir - ngOnInit',
'OtherChildHostDir - ngOnInit',
'Child - ngOnInit',
'PlainDir on child - ngOnInit',
'ChildHostDir - ngAfterViewInit',
'OtherChildHostDir - ngAfterViewInit',
'Child - ngAfterViewInit',
'PlainDir on child - ngAfterViewInit',
'ParentHostDir - ngAfterViewInit',
'OtherParentHostDir - ngAfterViewInit',
'Parent - ngAfterViewInit',
'PlainDir on parent - ngAfterViewInit',
]);
});
it('should invoke host directive ngOnChanges hooks before the host component', () => {
let logs: string[] = [];
// Utility so we don't have to repeat the logging code.
@Directive({standalone: true})
abstract class LogsLifecycles implements OnChanges {
@Input() someInput: any;
abstract name: string;
ngOnChanges(changes: SimpleChanges) {
logs.push(`${this.name} - ${changes.someInput.currentValue}`);
}
}
@Directive({standalone: true})
class HostDir extends LogsLifecycles {
override name = 'HostDir';
}
@Directive({standalone: true})
class OtherHostDir extends LogsLifecycles {
override name = 'OtherHostDir';
}
@Component({
selector: 'host-comp',
hostDirectives: [
{directive: HostDir, inputs: ['someInput']},
{directive: OtherHostDir, inputs: ['someInput']},
],
})
class HostComp extends LogsLifecycles {
override name = 'HostComp';
}
@Directive({selector: '[plain-dir]'})
class PlainDir extends LogsLifecycles {
override name = 'PlainDir';
}
@Component({
template: '<host-comp plain-dir="PlainDir" [someInput]="inputValue"></host-comp>',
})
class App {
inputValue = 'hello';
}
TestBed.configureTestingModule({declarations: [App, HostComp, PlainDir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(logs).toEqual(
['HostDir - hello', 'OtherHostDir - hello', 'HostComp - hello', 'PlainDir - hello']);
logs = [];
fixture.componentInstance.inputValue = 'changed';
fixture.detectChanges();
expect(logs).toEqual([
'HostDir - changed',
'OtherHostDir - changed',
'HostComp - changed',
'PlainDir - changed',
]);
});
});
describe('host bindings', () => {
it('should apply the host bindings from all host directives', () => {
const clicks: string[] = [];
@Directive({standalone: true, host: {'host-dir-attr': 'true', '(click)': 'handleClick()'}})
class HostDir {
handleClick() {
clicks.push('HostDir');
}
}
@Directive(
{standalone: true, host: {'other-host-dir-attr': 'true', '(click)': 'handleClick()'}})
class OtherHostDir {
handleClick() {
clicks.push('OtherHostDir');
}
}
@Directive({
selector: '[dir]',
host: {'host-attr': 'true', '(click)': 'handleClick()'},
hostDirectives: [HostDir, OtherHostDir]
})
class Dir {
handleClick() {
clicks.push('Dir');
}
}
@Component({template: '<button dir></button>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Dir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const host = fixture.nativeElement.querySelector('[dir]');
expect(host.outerHTML)
.toBe(
'<button host-dir-attr="true" other-host-dir-attr="true" host-attr="true" dir=""></button>');
host.click();
fixture.detectChanges();
expect(clicks).toEqual(['HostDir', 'OtherHostDir', 'Dir']);
});
it('should have the host bindings 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 {
}
@Directive(
{selector: '[dir]', host: {'id': 'host'}, hostDirectives: [HostDir, OtherHostDir]})
class Dir {
}
@Component({template: '<div dir></div>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Dir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('[dir]').getAttribute('id')).toBe('host');
});
});
describe('dependency injection', () => {
it('should allow the host to inject its host directives', () => {
let hostInstance!: Host;
let firstHostDirInstance!: FirstHostDir;
let secondHostDirInstance!: SecondHostDir;
@Directive({standalone: true})
class SecondHostDir {
constructor() {
secondHostDirInstance = this;
}
}
@Directive({standalone: true, hostDirectives: [SecondHostDir]})
class FirstHostDir {
constructor() {
firstHostDirInstance = this;
}
}
@Directive({selector: '[dir]', hostDirectives: [FirstHostDir]})
class Host {
firstHostDir = inject(FirstHostDir);
secondHostDir = inject(SecondHostDir);
constructor() {
hostInstance = this;
}
}
@Component({template: '<div dir></div>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Host]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(hostInstance instanceof Host).toBe(true);
expect(firstHostDirInstance instanceof FirstHostDir).toBe(true);
expect(secondHostDirInstance instanceof SecondHostDir).toBe(true);
expect(hostInstance.firstHostDir).toBe(firstHostDirInstance);
expect(hostInstance.secondHostDir).toBe(secondHostDirInstance);
});
it('should be able to inject a host directive into a child component', () => {
let hostDirectiveInstance!: HostDir;
@Component({selector: 'child', template: ''})
class Child {
hostDir = inject(HostDir);
}
@Directive({standalone: true})
class HostDir {
constructor() {
hostDirectiveInstance = this;
}
}
@Component({
selector: 'host',
template: '<child></child>',
hostDirectives: [HostDir],
})
class Host {
@ViewChild(Child) child!: Child;
}
@Component({template: '<host></host>'})
class App {
@ViewChild(Host) host!: Host;
}
TestBed.configureTestingModule({declarations: [App, Host, Child]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const injectedInstance = fixture.componentInstance.host.child.hostDir;
expect(injectedInstance instanceof HostDir).toBe(true);
expect(injectedInstance).toBe(hostDirectiveInstance);
});
it('should allow the host directives to inject their host', () => {
let hostInstance!: Host;
let firstHostDirInstance!: FirstHostDir;
let secondHostDirInstance!: SecondHostDir;
@Directive({standalone: true})
class SecondHostDir {
host = inject(Host);
constructor() {
secondHostDirInstance = this;
}
}
@Directive({standalone: true, hostDirectives: [SecondHostDir]})
class FirstHostDir {
host = inject(Host);
constructor() {
firstHostDirInstance = this;
}
}
@Directive({selector: '[dir]', hostDirectives: [FirstHostDir]})
class Host {
constructor() {
hostInstance = this;
}
}
@Component({template: '<div dir></div>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Host]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(hostInstance instanceof Host).toBe(true);
expect(firstHostDirInstance instanceof FirstHostDir).toBe(true);
expect(secondHostDirInstance instanceof SecondHostDir).toBe(true);
expect(firstHostDirInstance.host).toBe(hostInstance);
expect(secondHostDirInstance.host).toBe(hostInstance);
});
it('should give precedence to the DI tokens from the host over the host directive tokens',
() => {
const token = new InjectionToken<string>('token');
let hostInstance!: Host;
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;
}
}
@Directive({
selector: '[dir]',
hostDirectives: [FirstHostDir],
providers: [{provide: token, useValue: 'HostDir'}]
})
class Host {
tokenValue = inject(token);
constructor() {
hostInstance = this;
}
}
@Component({template: '<div dir></div>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Host]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(hostInstance instanceof Host).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 host 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 {
}
@Directive({selector: '[dir]', hostDirectives: [FirstHostDir]})
class Host {
firstTokenValue = inject(firstToken);
secondTokenValue = inject(secondToken);
}
@Component({template: '<div dir></div>'})
class App {
@ViewChild(Host) host!: Host;
}
TestBed.configureTestingModule({declarations: [App, Host]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.host.firstTokenValue).toBe('FirstDir');
expect(fixture.componentInstance.host.secondTokenValue).toBe('SecondDir');
});
it('should not give precedence to tokens from host directives over ones in viewProviders',
() => {
const token = new InjectionToken<string>('token');
let tokenValue: string|undefined;
@Directive({standalone: true, providers: [{provide: token, useValue: 'host-dir'}]})
class HostDir {
}
@Component({
selector: 'host',
hostDirectives: [HostDir],
providers: [{provide: token, useValue: 'host'}],
template: '<span child></span>',
})
class Host {
}
@Directive({selector: '[child]'})
class Child {
constructor() {
tokenValue = inject(token);
}
}
@Component({template: '<host></host>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Host, Child]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(tokenValue).toBe('host');
});
it('should not be able to access viewProviders from the host in the host directives', () => {
const token = new InjectionToken<string>('token');
let tokenValue: string|null = null;
@Directive({standalone: true})
class HostDir {
constructor() {
tokenValue = inject(token, {optional: true});
}
}
@Component({
selector: 'host',
hostDirectives: [HostDir],
viewProviders: [{provide: token, useValue: 'host'}],
template: '',
})
class Host {
}
@Component({template: '<host></host>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Host]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(tokenValue).toBe(null);
});
it('should throw a circular dependency error if a host and a host directive inject each other',
() => {
@Directive({standalone: true})
class HostDir {
host = inject(Host);
}
@Directive({selector: '[dir]', hostDirectives: [HostDir]})
class Host {
hostDir = inject(HostDir);
}
@Component({template: '<div dir></div>'})
class App {
}
TestBed.configureTestingModule({declarations: [App, Host]});
expect(() => TestBed.createComponent(App))
.toThrowError(/NG0200: Circular dependency in DI detected for HostDir/);
});
it('should inject a valid ChangeDetectorRef when attached to a component', () => {
type InternalChangeDetectorRef = ChangeDetectorRef&{_lView: unknown};
@Directive({standalone: true})
class HostDir {
changeDetectorRef = inject(ChangeDetectorRef) as InternalChangeDetectorRef;
}
@Component({selector: 'my-comp', hostDirectives: [HostDir], template: ''})
class Comp {
changeDetectorRef = inject(ChangeDetectorRef) as InternalChangeDetectorRef;
}
@Component({template: '<my-comp></my-comp>'})
class App {
@ViewChild(HostDir) hostDir!: HostDir;
@ViewChild(Comp) comp!: Comp;
}
TestBed.configureTestingModule({declarations: [App, Comp]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const hostDirectiveCdr = fixture.componentInstance.hostDir.changeDetectorRef;
const componentCdr = fixture.componentInstance.comp.changeDetectorRef;
// We can't assert that the change detectors are the same by comparing
// them directly, because a new one is created each time. Instead of we
// compare that they're associated with the same LView.
expect(hostDirectiveCdr._lView).toBeTruthy();
expect(componentCdr._lView).toBeTruthy();
expect(hostDirectiveCdr._lView).toBe(componentCdr._lView);
expect(() => {
hostDirectiveCdr.markForCheck();
hostDirectiveCdr.detectChanges();
}).not.toThrow();
});
});
describe('outputs', () => {
it('should not emit to an output of a host directive that has not been exposed', () => {
let hostDirectiveInstance: HostDir|undefined;
@Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit()'}})
class HostDir {
@Output() hasBeenClicked = new EventEmitter<void>();
constructor() {
hostDirectiveInstance = this;
}
}
@Directive({selector: '[dir]', hostDirectives: [HostDir]})
class Dir {
}
@Component({template: '<button dir (hasBeenClicked)="spy()"></button>'})
class App {
spy = jasmine.createSpy('click spy');
}
TestBed.configureTestingModule({declarations: [App, Dir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(hostDirectiveInstance instanceof HostDir).toBe(true);
expect(fixture.componentInstance.spy).not.toHaveBeenCalled();
});
it('should emit to an output of a host directive that has been exposed', () => {
@Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("hello")'}})
class HostDir {
@Output() hasBeenClicked = new EventEmitter<string>();
}