|
| 1 | +import {Component} from '@angular/core'; |
| 2 | +import {async, ComponentFixture, TestBed} from '@angular/core/testing'; |
| 3 | +import {By} from '@angular/platform-browser'; |
| 4 | + |
| 5 | +/* |
| 6 | +* Example Use case |
| 7 | +* When we want to create a tightly coupled components which is always supposed to |
| 8 | +* be inside another component. Also when we don't want to pass some thing as input for |
| 9 | +* multiple child component. We can pass it to parent component once and child component can |
| 10 | +* get parent instance and access the values of parent. |
| 11 | +* |
| 12 | +* <app-form-error-container [control]="control"> |
| 13 | +* <app-form-error [type]="required">This field is required</app-form-error> |
| 14 | +* <app-form-error [type]="minlength">This field should have a minimum of 10 characters</app-form-error> |
| 15 | +* </app-form-error-container> |
| 16 | +* |
| 17 | +* In the above example we can pass the control to container once and all child will access it |
| 18 | +* and do a check to make it self visible or not. |
| 19 | +*/ |
| 20 | + |
| 21 | +@Component({ |
| 22 | + selector: 'app-parent', |
| 23 | + template: ` |
| 24 | + <div> |
| 25 | + <span>{{value}}</span> |
| 26 | + <ng-content></ng-content> |
| 27 | + </div>` |
| 28 | +}) |
| 29 | +export class ParentComponent { |
| 30 | + value = 'parent'; |
| 31 | +} |
| 32 | + |
| 33 | +@Component({ |
| 34 | + selector: 'app-child', |
| 35 | + template: ` |
| 36 | + <div>{{parent.value}}</div>` |
| 37 | +}) |
| 38 | +export class ChildComponent { |
| 39 | + parent: ParentComponent; |
| 40 | + |
| 41 | + constructor(private parentComponent: ParentComponent) { |
| 42 | + this.parent = parentComponent; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +describe('NestedComponentWithInjectedParentTesting', () => { |
| 47 | + let component: ChildComponent; |
| 48 | + let fixture: ComponentFixture<ChildComponent>; |
| 49 | + |
| 50 | + beforeEach(async(() => { |
| 51 | + TestBed.configureTestingModule({ |
| 52 | + declarations: [ParentComponent, ChildComponent], |
| 53 | + providers: [ParentComponent] |
| 54 | + }) |
| 55 | + .compileComponents(); |
| 56 | + })); |
| 57 | + |
| 58 | + beforeEach(() => { |
| 59 | + fixture = TestBed.createComponent(ChildComponent); |
| 60 | + component = fixture.componentInstance; |
| 61 | + fixture.detectChanges(); |
| 62 | + }); |
| 63 | + |
| 64 | + it('should create', () => { |
| 65 | + expect(component).toBeTruthy(); |
| 66 | + }); |
| 67 | + |
| 68 | + it('should have parent with value parent', function () { |
| 69 | + expect(component.parent.value).toBe('parent'); |
| 70 | + }); |
| 71 | + |
| 72 | + it('should data bind parent value', function () { |
| 73 | + expect(fixture.debugElement.query(By.css('div')).nativeElement.innerText).toBe('parent'); |
| 74 | + }); |
| 75 | +}); |
0 commit comments