Skip to content

Commit

Permalink
feat(common): add component input binding support for NgComponentOutl…
Browse files Browse the repository at this point in the history
…et (angular#51148)

This commit add component input binding support for NgComponentOutlet.

PR Close angular#51148
  • Loading branch information
HyperLife1119 authored and sunilbaba committed Jul 26, 2023
1 parent ec6952d commit b27d1db
Show file tree
Hide file tree
Showing 4 changed files with 213 additions and 36 deletions.
8 changes: 6 additions & 2 deletions goldens/public-api/common/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ export class NgClass implements DoCheck {
}

// @public
export class NgComponentOutlet implements OnChanges, OnDestroy {
export class NgComponentOutlet implements OnChanges, DoCheck, OnDestroy {
constructor(_viewContainerRef: ViewContainerRef);
// (undocumented)
ngComponentOutlet: Type<any> | null;
Expand All @@ -500,15 +500,19 @@ export class NgComponentOutlet implements OnChanges, OnDestroy {
// (undocumented)
ngComponentOutletInjector?: Injector;
// (undocumented)
ngComponentOutletInputs?: Record<string, unknown>;
// (undocumented)
ngComponentOutletNgModule?: Type<any>;
// @deprecated (undocumented)
ngComponentOutletNgModuleFactory?: NgModuleFactory<any>;
// (undocumented)
ngDoCheck(): void;
// (undocumented)
ngOnChanges(changes: SimpleChanges): void;
// (undocumented)
ngOnDestroy(): void;
// (undocumented)
static ɵdir: i0.ɵɵDirectiveDeclaration<NgComponentOutlet, "[ngComponentOutlet]", never, { "ngComponentOutlet": { "alias": "ngComponentOutlet"; "required": false; }; "ngComponentOutletInjector": { "alias": "ngComponentOutletInjector"; "required": false; }; "ngComponentOutletContent": { "alias": "ngComponentOutletContent"; "required": false; }; "ngComponentOutletNgModule": { "alias": "ngComponentOutletNgModule"; "required": false; }; "ngComponentOutletNgModuleFactory": { "alias": "ngComponentOutletNgModuleFactory"; "required": false; }; }, {}, never, never, true, never>;
static ɵdir: i0.ɵɵDirectiveDeclaration<NgComponentOutlet, "[ngComponentOutlet]", never, { "ngComponentOutlet": { "alias": "ngComponentOutlet"; "required": false; }; "ngComponentOutletInputs": { "alias": "ngComponentOutletInputs"; "required": false; }; "ngComponentOutletInjector": { "alias": "ngComponentOutletInjector"; "required": false; }; "ngComponentOutletContent": { "alias": "ngComponentOutletContent"; "required": false; }; "ngComponentOutletNgModule": { "alias": "ngComponentOutletNgModule"; "required": false; }; "ngComponentOutletNgModuleFactory": { "alias": "ngComponentOutletNgModuleFactory"; "required": false; }; }, {}, never, never, true, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<NgComponentOutlet, never>;
}
Expand Down
121 changes: 91 additions & 30 deletions packages/common/src/directives/ng_component_outlet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {ComponentRef, createNgModule, Directive, Injector, Input, NgModuleFactory, NgModuleRef, OnChanges, OnDestroy, SimpleChanges, Type, ViewContainerRef} from '@angular/core';

import {ComponentRef, createNgModule, Directive, DoCheck, Injector, Input, NgModuleFactory, NgModuleRef, OnChanges, OnDestroy, SimpleChanges, Type, ViewContainerRef} from '@angular/core';

/**
* Instantiates a {@link Component} type and inserts its Host View into the current View.
Expand All @@ -22,6 +21,9 @@ import {ComponentRef, createNgModule, Directive, Injector, Input, NgModuleFactor
*
* You can control the component creation process by using the following optional attributes:
*
* * `ngComponentOutletInputs`: Optional component inputs object, which will be bind to the
* component.
*
* * `ngComponentOutletInjector`: Optional custom {@link Injector} that will be used as parent for
* the Component. Defaults to the injector of the current view container.
*
Expand All @@ -42,6 +44,13 @@ import {ComponentRef, createNgModule, Directive, Injector, Input, NgModuleFactor
* <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container>
* ```
*
* With inputs
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
* inputs: inputsExpression;">
* </ng-container>
* ```
*
* Customized injector/content
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
Expand Down Expand Up @@ -72,9 +81,10 @@ import {ComponentRef, createNgModule, Directive, Injector, Input, NgModuleFactor
selector: '[ngComponentOutlet]',
standalone: true,
})
export class NgComponentOutlet implements OnChanges, OnDestroy {
export class NgComponentOutlet implements OnChanges, DoCheck, OnDestroy {
@Input() ngComponentOutlet: Type<any>|null = null;

@Input() ngComponentOutletInputs?: Record<string, unknown>;
@Input() ngComponentOutletInjector?: Injector;
@Input() ngComponentOutletContent?: any[][];

Expand All @@ -87,45 +97,96 @@ export class NgComponentOutlet implements OnChanges, OnDestroy {
private _componentRef: ComponentRef<any>|undefined;
private _moduleRef: NgModuleRef<any>|undefined;

/**
* A helper data structure that allows us to track inputs that were part of the
* ngComponentOutletInputs expression. Tracking inputs is necessary for proper removal of ones
* that are no longer referenced.
*/
private _inputsUsed = new Map<string, boolean>();

constructor(private _viewContainerRef: ViewContainerRef) {}

private _needToReCreateNgModuleInstance(changes: SimpleChanges): boolean {
// Note: square brackets property accessor is safe for Closure compiler optimizations (the
// `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that
// were changed).
return changes['ngComponentOutletNgModule'] !== undefined ||
changes['ngComponentOutletNgModuleFactory'] !== undefined;
}

private _needToReCreateComponentInstance(changes: SimpleChanges): boolean {
// Note: square brackets property accessor is safe for Closure compiler optimizations (the
// `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that
// were changed).
return changes['ngComponentOutlet'] !== undefined ||
changes['ngComponentOutletContent'] !== undefined ||
changes['ngComponentOutletInjector'] !== undefined ||
this._needToReCreateNgModuleInstance(changes);
}

/** @nodoc */
ngOnChanges(changes: SimpleChanges) {
const {
_viewContainerRef: viewContainerRef,
ngComponentOutletNgModule: ngModule,
ngComponentOutletNgModuleFactory: ngModuleFactory,
} = this;
viewContainerRef.clear();
this._componentRef = undefined;

if (this.ngComponentOutlet) {
const injector = this.ngComponentOutletInjector || viewContainerRef.parentInjector;

if (changes['ngComponentOutletNgModule'] || changes['ngComponentOutletNgModuleFactory']) {
if (this._moduleRef) this._moduleRef.destroy();

if (ngModule) {
this._moduleRef = createNgModule(ngModule, getParentInjector(injector));
} else if (ngModuleFactory) {
this._moduleRef = ngModuleFactory.create(getParentInjector(injector));
} else {
this._moduleRef = undefined;
if (this._needToReCreateComponentInstance(changes)) {
this._viewContainerRef.clear();
this._inputsUsed.clear();
this._componentRef = undefined;

if (this.ngComponentOutlet) {
const injector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector;

if (this._needToReCreateNgModuleInstance(changes)) {
this._moduleRef?.destroy();

if (this.ngComponentOutletNgModule) {
this._moduleRef =
createNgModule(this.ngComponentOutletNgModule, getParentInjector(injector));
} else if (this.ngComponentOutletNgModuleFactory) {
this._moduleRef =
this.ngComponentOutletNgModuleFactory.create(getParentInjector(injector));
} else {
this._moduleRef = undefined;
}
}

this._componentRef = this._viewContainerRef.createComponent(this.ngComponentOutlet, {
injector,
ngModuleRef: this._moduleRef,
projectableNodes: this.ngComponentOutletContent,
});
}
}
}

/** @nodoc */
ngDoCheck() {
if (this._componentRef) {
if (this.ngComponentOutletInputs) {
for (const inputName of Object.keys(this.ngComponentOutletInputs)) {
this._inputsUsed.set(inputName, true);
}
}

this._componentRef = viewContainerRef.createComponent(this.ngComponentOutlet, {
index: viewContainerRef.length,
injector,
ngModuleRef: this._moduleRef,
projectableNodes: this.ngComponentOutletContent,
});
this._applyInputStateDiff(this._componentRef);
}
}

/** @nodoc */
ngOnDestroy() {
if (this._moduleRef) this._moduleRef.destroy();
this._moduleRef?.destroy();
}

private _applyInputStateDiff(componentRef: ComponentRef<unknown>) {
for (const [inputName, touched] of this._inputsUsed) {
if (!touched) {
// The input that was previously active no longer exists and needs to be set to undefined.
componentRef.setInput(inputName, undefined);
this._inputsUsed.delete(inputName);
} else {
// Since touched is true, it can be asserted that the inputs object is not empty.
componentRef.setInput(inputName, this.ngComponentOutletInputs![inputName]);
this._inputsUsed.set(inputName, false);
}
}
}
}

Expand Down
110 changes: 108 additions & 2 deletions packages/common/test/directives/ng_component_outlet_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import {CommonModule} from '@angular/common';
import {NgComponentOutlet} from '@angular/common/src/directives/ng_component_outlet';
import {Compiler, Component, ComponentRef, Inject, InjectionToken, Injector, NgModule, NgModuleFactory, NO_ERRORS_SCHEMA, Optional, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef} from '@angular/core';
import {Compiler, Component, ComponentRef, Inject, InjectionToken, Injector, Input, NgModule, NgModuleFactory, NO_ERRORS_SCHEMA, Optional, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef} from '@angular/core';
import {TestBed, waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';

Expand Down Expand Up @@ -295,20 +295,92 @@ describe('insert/remove', () => {
});
});

describe('inputs', () => {
it('should be binding the component input', () => {
const fixture = TestBed.createComponent(TestInputsComponent);
fixture.componentInstance.currentComponent = ComponentWithInputs;
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: , bar: , baz: Baz');

fixture.componentInstance.inputs = {};
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: , bar: , baz: Baz');

fixture.componentInstance.inputs = {foo: 'Foo', bar: 'Bar'};
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: Foo, bar: Bar, baz: Baz');

fixture.componentInstance.inputs = {foo: 'Foo'};
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: Foo, bar: , baz: Baz');

fixture.componentInstance.inputs = {foo: 'Foo', baz: null};
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: Foo, bar: , baz: ');

fixture.componentInstance.inputs = undefined;
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: , bar: , baz: ');
});

it('should be binding the component input (with mutable inputs)', () => {
const fixture = TestBed.createComponent(TestInputsComponent);
fixture.componentInstance.currentComponent = ComponentWithInputs;
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: , bar: , baz: Baz');

fixture.componentInstance.inputs = {foo: 'Hello', bar: 'World'};
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: Hello, bar: World, baz: Baz');

fixture.componentInstance.inputs['bar'] = 'Angular';
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: Hello, bar: Angular, baz: Baz');

delete fixture.componentInstance.inputs['foo'];
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: , bar: Angular, baz: Baz');
});

it('should be binding the component input (with component type change)', () => {
const fixture = TestBed.createComponent(TestInputsComponent);
fixture.componentInstance.currentComponent = ComponentWithInputs;
fixture.componentInstance.inputs = {foo: 'Foo', bar: 'Bar'};
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('foo: Foo, bar: Bar, baz: Baz');

fixture.componentInstance.currentComponent = AnotherComponentWithInputs;
fixture.detectChanges();

expect(fixture.nativeElement.textContent).toBe('[ANOTHER] foo: Foo, bar: Bar, baz: Baz');
});
});

const TEST_TOKEN = new InjectionToken('TestToken');
@Component({selector: 'injected-component', template: 'foo'})
class InjectedComponent {
constructor(@Optional() @Inject(TEST_TOKEN) public testToken: any) {}
}


@Component({selector: 'injected-component-again', template: 'bar'})
class InjectedComponentAgain {
}

const TEST_CMP_TEMPLATE = `<ng-template *ngComponentOutlet="
currentComponent;
injector: injector;
inputs: inputs;
content: projectables;
ngModule: ngModule;
ngModuleFactory: ngModuleFactory;
Expand All @@ -317,6 +389,7 @@ const TEST_CMP_TEMPLATE = `<ng-template *ngComponentOutlet="
class TestComponent {
currentComponent: Type<unknown>|null = null;
injector?: Injector;
inputs?: Record<string, unknown>;
projectables?: any[][];
ngModule?: Type<unknown>;
ngModuleFactory?: NgModuleFactory<unknown>;
Expand Down Expand Up @@ -371,3 +444,36 @@ class Module3InjectedComponent {
})
export class TestModule3 {
}

@Component({
selector: 'cmp-with-inputs',
standalone: true,
template: `foo: {{ foo }}, bar: {{ bar }}, baz: {{ baz }}`
})
class ComponentWithInputs {
@Input() foo?: any;
@Input() bar?: any;
@Input() baz?: any = 'Baz';
}

@Component({
selector: 'another-cmp-with-inputs',
standalone: true,
template: `[ANOTHER] foo: {{ foo }}, bar: {{ bar }}, baz: {{ baz }}`
})
class AnotherComponentWithInputs {
@Input() foo?: any;
@Input() bar?: any;
@Input() baz?: any = 'Baz';
}

@Component({
selector: 'test-cmp',
standalone: true,
imports: [NgComponentOutlet],
template: `<ng-template *ngComponentOutlet="currentComponent; inputs: inputs;"></ng-template>`
})
class TestInputsComponent {
currentComponent: Type<unknown>|null = null;
inputs?: Record<string, unknown>;
}
10 changes: 8 additions & 2 deletions packages/examples/common/ngComponentOutlet/ts/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {Component, Injectable, Injector, NgModule, OnInit, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core';
import {Component, Injectable, Injector, Input, NgModule, OnInit, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';


Expand All @@ -33,9 +33,11 @@ export class Greeter {

@Component({
selector: 'complete-component',
template: `Complete: <ng-content></ng-content> <ng-content></ng-content>{{ greeter.suffix }}`
template: `{{ label }}: <ng-content></ng-content> <ng-content></ng-content>{{ greeter.suffix }}`
})
export class CompleteComponent {
@Input() label!: string;

constructor(public greeter: Greeter) {}
}

Expand All @@ -45,12 +47,16 @@ export class CompleteComponent {
<ng-template #ahoj>Ahoj</ng-template>
<ng-template #svet>Svet</ng-template>
<ng-container *ngComponentOutlet="CompleteComponent;
inputs: myInputs;
injector: myInjector;
content: myContent"></ng-container>`
})
export class NgComponentOutletCompleteExample implements OnInit {
// This field is necessary to expose CompleteComponent to the template.
CompleteComponent = CompleteComponent;

myInputs = {'label': 'Complete'};

myInjector: Injector;
@ViewChild('ahoj', {static: true}) ahojTemplateRef!: TemplateRef<any>;
@ViewChild('svet', {static: true}) svetTemplateRef!: TemplateRef<any>;
Expand Down

0 comments on commit b27d1db

Please sign in to comment.