fix(ivy): pass ngContentSelectors through to `defineComponent()` calls (#27867)

Libraries that create components dynamically using component factories,
such as `@angular/upgrade` need to pass blocks of projected content
through to the `ComponentFactory.create()` method. These blocks
are extracted from the content by matching CSS selectors defined in
`<ng-content select="..">` tags found in the component's template.

The Angular compiler collects these CSS selectors when compiling a component's
template, and exposes them via the `ComponentFactory.ngContentSelectors`
property.

This change ensures that this property is filled correctly when the
component factory is created by compiling a component with the Ivy engine.

PR Close #27867
This commit is contained in:
Pete Bacon Darwin 2018-12-22 16:02:34 +00:00 committed by Andrew Kushnir
parent e8a57f0ee6
commit feebe03523
12 changed files with 301 additions and 262 deletions

View File

@ -1144,6 +1144,7 @@ describe('compiler compliance', () => {
type: SimpleComponent,
selectors: [["simple"]],
factory: function SimpleComponent_Factory(t) { return new (t || SimpleComponent)(); },
ngContentSelectors: _c0,
consts: 2,
vars: 0,
template: function SimpleComponent_Template(rf, ctx) {
@ -1167,6 +1168,7 @@ describe('compiler compliance', () => {
type: ComplexComponent,
selectors: [["complex"]],
factory: function ComplexComponent_Factory(t) { return new (t || ComplexComponent)(); },
ngContentSelectors: _c4,
consts: 4,
vars: 0,
template: function ComplexComponent_Template(rf, ctx) {
@ -1561,6 +1563,7 @@ describe('compiler compliance', () => {
($r3$.ɵqueryRefresh(($tmp$ = $r3$.ɵloadQueryList(queryStartIndex))) && ($instance$.someDir = $tmp$.first));
($r3$.ɵqueryRefresh(($tmp$ = $r3$.ɵloadQueryList((queryStartIndex + 1)))) && ($instance$.someDirList = $tmp$));
},
ngContentSelectors: _c0,
consts: 2,
vars: 0,
template: function ContentQueryComponent_Template(rf, ctx) {

View File

@ -264,6 +264,13 @@ export function compileComponentFromMetadata(
const templateFunctionExpression = templateBuilder.buildTemplateFunction(template.nodes, []);
// We need to provide this so that dynamically generated components know what
// projected content blocks to pass through to the component when it is instantiated.
const ngContentSelectors = templateBuilder.getNgContentSelectors();
if (ngContentSelectors) {
definitionMap.set('ngContentSelectors', ngContentSelectors);
}
// e.g. `consts: 2`
definitionMap.set('consts', o.literal(templateBuilder.getConstCount()));

View File

@ -915,6 +915,12 @@ export class TemplateDefinitionBuilder implements t.Visitor<void>, LocalResolver
getVarCount() { return this._pureFunctionSlots; }
getNgContentSelectors(): o.Expression|null {
return this._hasNgContent ?
this.constantPool.getConstLiteral(asLiteral(this._ngContentSelectors), true) :
null;
}
private bindingContext() { return `${this._bindingContext++}`; }
// Bindings must only be resolved after all local refs have been visited, so all

View File

@ -119,7 +119,10 @@ export class ComponentFactory<T> extends viewEngine_ComponentFactory<T> {
super();
this.componentType = componentDef.type;
this.selector = componentDef.selectors[0][0] as string;
this.ngContentSelectors = [];
// The component definition does not include the wildcard ('*') selector in its list.
// It is implicitly expected as the first item in the projectable nodes array.
this.ngContentSelectors =
componentDef.ngContentSelectors ? ['*', ...componentDef.ngContentSelectors] : [];
}
create(

View File

@ -182,6 +182,11 @@ export function defineComponent<T>(componentDefinition: {
*/
template: ComponentTemplate<T>;
/**
* An array of `ngContent[selector]` values that were found in the template.
*/
ngContentSelectors?: string[];
/**
* Additional set of instructions specific to view query processing. This could be seen as a
* set of instruction to be inserted into the template function.
@ -249,6 +254,7 @@ export function defineComponent<T>(componentDefinition: {
vars: componentDefinition.vars,
factory: componentDefinition.factory,
template: componentDefinition.template || null !,
ngContentSelectors: componentDefinition.ngContentSelectors,
hostBindings: componentDefinition.hostBindings || null,
contentQueries: componentDefinition.contentQueries || null,
contentQueriesRefresh: componentDefinition.contentQueriesRefresh || null,

View File

@ -189,6 +189,11 @@ export interface ComponentDef<T> extends DirectiveDef<T> {
*/
readonly template: ComponentTemplate<T>;
/**
* An array of `ngContent[selector]` values that were found in the template.
*/
readonly ngContentSelectors?: string[];
/**
* A set of styles that the component needs to be present for component to render correctly.
*/

View File

@ -18,7 +18,28 @@ describe('ComponentFactory', () => {
const cfr = injectComponentFactoryResolver();
describe('constructor()', () => {
it('should correctly populate public properties', () => {
it('should correctly populate default properties', () => {
class TestComponent {
static ngComponentDef = defineComponent({
type: TestComponent,
selectors: [['test', 'foo'], ['bar']],
consts: 0,
vars: 0,
template: () => undefined,
factory: () => new TestComponent(),
});
}
const cf = cfr.resolveComponentFactory(TestComponent);
expect(cf.selector).toBe('test');
expect(cf.componentType).toBe(TestComponent);
expect(cf.ngContentSelectors).toEqual([]);
expect(cf.inputs).toEqual([]);
expect(cf.outputs).toEqual([]);
});
it('should correctly populate defined properties', () => {
class TestComponent {
static ngComponentDef = defineComponent({
type: TestComponent,
@ -27,6 +48,7 @@ describe('ComponentFactory', () => {
consts: 0,
vars: 0,
template: () => undefined,
ngContentSelectors: ['a', 'b'],
factory: () => new TestComponent(),
inputs: {
in1: 'in1',
@ -42,7 +64,7 @@ describe('ComponentFactory', () => {
const cf = cfr.resolveComponentFactory(TestComponent);
expect(cf.componentType).toBe(TestComponent);
expect(cf.ngContentSelectors).toEqual([]);
expect(cf.ngContentSelectors).toEqual(['*', 'a', 'b']);
expect(cf.selector).toBe('test');
expect(cf.inputs).toEqual([

View File

@ -30,8 +30,7 @@ withEachNg1Version(() => {
describe('(basic use)', () => {
it('should have AngularJS loaded', () => expect(angular.version.major).toBe(1));
fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should instantiate ng2 in ng1 template and project content', async(() => {
it('should instantiate ng2 in ng1 template and project content', async(() => {
const ng1Module = angular.module('ng1', []);
@Component({
@ -724,8 +723,7 @@ withEachNg1Version(() => {
});
}));
fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should support multi-slot projection', async(() => {
it('should support multi-slot projection', async(() => {
const ng1Module = angular.module('ng1', []);
@Component({
@ -754,10 +752,8 @@ withEachNg1Version(() => {
});
}));
fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should correctly project structural directives', async(() => {
@Component(
{selector: 'ng2', template: 'ng2-{{ itemId }}(<ng-content></ng-content>)'})
it('should correctly project structural directives', async(() => {
@Component({selector: 'ng2', template: 'ng2-{{ itemId }}(<ng-content></ng-content>)'})
class Ng2Component {
// TODO(issue/24571): remove '!'.
@Input() itemId !: string;
@ -768,8 +764,7 @@ withEachNg1Version(() => {
}
const adapter: UpgradeAdapter = new UpgradeAdapter(Ng2Module);
const ng1Module =
angular.module('ng1', [])
const ng1Module = angular.module('ng1', [])
.directive('ng2', adapter.downgradeNg2Component(Ng2Component))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['items'] = [
@ -3110,7 +3105,7 @@ withEachNg1Version(() => {
});
}));
fixmeIvy('FW-714: ng1 projected content is not being rendered')
fixmeIvy('FW-873: projected component injector hierarchy not wired up correctly')
.it('should respect hierarchical dependency injection for ng2', async(() => {
const ng1Module = angular.module('ng1', []);
@ -3213,8 +3208,7 @@ withEachNg1Version(() => {
});
describe('examples', () => {
fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should verify UpgradeAdapter example', async(() => {
it('should verify UpgradeAdapter example', async(() => {
const adapter: UpgradeAdapter = new UpgradeAdapter(forwardRef(() => Ng2Module));
const module = angular.module('myExample', []);

View File

@ -22,8 +22,7 @@ withEachNg1Version(() => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should instantiate ng2 in ng1 template and project content', async(() => {
it('should instantiate ng2 in ng1 template and project content', async(() => {
// the ng2 component that will be used in ng1 (downgraded)
@Component({selector: 'ng2', template: `{{ prop }}(<ng-content></ng-content>)`})
@ -52,16 +51,14 @@ withEachNg1Version(() => {
$rootScope['ngContent'] = 'ng1-content';
});
const element =
html('<div>{{ \'ng1[\' }}<ng2>~{{ ngContent }}~</ng2>{{ \']\' }}</div>');
const element = html('<div>{{ \'ng1[\' }}<ng2>~{{ ngContent }}~</ng2>{{ \']\' }}</div>');
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('ng1[NG2(~ng1-content~)]');
});
}));
fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should correctly project structural directives', async(() => {
it('should correctly project structural directives', async(() => {
@Component({selector: 'ng2', template: 'ng2-{{ itemId }}(<ng-content></ng-content>)'})
class Ng2Component {
// TODO(issue/24571): remove '!'.
@ -77,8 +74,7 @@ withEachNg1Version(() => {
ngDoBootstrap() {}
}
const ng1Module =
angular.module('ng1', [])
const ng1Module = angular.module('ng1', [])
.directive('ng2', downgradeComponent({component: Ng2Component}))
.run(($rootScope: angular.IRootScopeService) => {
$rootScope['items'] = [
@ -145,8 +141,7 @@ withEachNg1Version(() => {
});
}));
fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should support multi-slot projection', async(() => {
it('should support multi-slot projection', async(() => {
@Component({
selector: 'ng2',

View File

@ -709,7 +709,7 @@ withEachNg1Version(() => {
});
}));
fixmeIvy('FW-714: ng1 projected content is not being rendered')
fixmeIvy('FW-873: projected component injector hierarchy not wired up correctly')
.it('should respect hierarchical dependency injection for ng2', async(() => {
@Component({selector: 'parent', template: 'parent(<ng-content></ng-content>)'})
class ParentComponent {

View File

@ -952,7 +952,6 @@ withEachNg1Version(() => {
}));
fixmeIvy('FW-715: ngOnChanges being called a second time unexpectedly')
.fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should run the lifecycle hooks in the correct order', async(() => {
const logs: string[] = [];
let rootScope: angular.IRootScopeService;

View File

@ -24,8 +24,7 @@ withEachNg1Version(() => {
it('should have AngularJS loaded', () => expect(angular.version.major).toBe(1));
fixmeIvy('FW-714: ng1 projected content is not being rendered')
.it('should verify UpgradeAdapter example', async(() => {
it('should verify UpgradeAdapter example', async(() => {
// This is wrapping (upgrading) an AngularJS component to be used in an Angular
// component