fix(compiler): support dotted property binding

fixes angular/flex-layout#34
This commit is contained in:
Victor Berchet 2016-12-09 14:42:13 -08:00
parent 95f48292b1
commit 3bee521aa4
2 changed files with 1499 additions and 1527 deletions

View File

@ -245,18 +245,12 @@ export class BindingParser {
let unit: string = null;
let bindingType: PropertyBindingType;
let boundPropertyName: string;
let boundPropertyName: string = null;
const parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
let securityContexts: SecurityContext[];
if (parts.length === 1) {
const partValue = parts[0];
boundPropertyName = this._schemaRegistry.getMappedPropName(partValue);
securityContexts = calcPossibleSecurityContexts(
this._schemaRegistry, elementSelector, boundPropertyName, false);
bindingType = PropertyBindingType.Property;
this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, false);
} else {
// Check check for special cases (prefix style, attr, class)
if (parts.length > 1) {
if (parts[0] == ATTRIBUTE_PREFIX) {
boundPropertyName = parts[1];
this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
@ -280,12 +274,18 @@ export class BindingParser {
boundPropertyName = parts[1];
bindingType = PropertyBindingType.Style;
securityContexts = [SecurityContext.STYLE];
} else {
this._reportError(`Invalid property name '${boundProp.name}'`, boundProp.sourceSpan);
bindingType = null;
securityContexts = [];
}
}
// If not a special case, use the full property name
if (boundPropertyName === null) {
boundPropertyName = this._schemaRegistry.getMappedPropName(boundProp.name);
securityContexts = calcPossibleSecurityContexts(
this._schemaRegistry, elementSelector, boundPropertyName, false);
bindingType = PropertyBindingType.Property;
this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, false);
}
return new BoundElementPropertyAst(
boundPropertyName, bindingType, securityContexts.length === 1 ? securityContexts[0] : null,
securityContexts.length > 1, boundProp.expression, unit, boundProp.sourceSpan);

View File

@ -6,13 +6,13 @@
* found in the LICENSE file at https://angular.io/license
*/
import {CompileAnimationEntryMetadata, CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeMetadata, CompilePipeSummary, CompileProviderMetadata, CompileQueryMetadata, CompileTemplateMetadata, CompileTokenMetadata, CompileTypeMetadata, tokenReference} from '@angular/compiler/src/compile_metadata';
import {CompileAnimationEntryMetadata, CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeMetadata, CompilePipeSummary, CompileProviderMetadata, CompileTemplateMetadata, CompileTokenMetadata, CompileTypeMetadata, tokenReference} from '@angular/compiler/src/compile_metadata';
import {DomElementSchemaRegistry} from '@angular/compiler/src/schema/dom_element_schema_registry';
import {ElementSchemaRegistry} from '@angular/compiler/src/schema/element_schema_registry';
import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, PropertyBindingType, ProviderAstType, ReferenceAst, TemplateAst, TemplateAstVisitor, TextAst, VariableAst, templateVisitAll} from '@angular/compiler/src/template_parser/template_ast';
import {TEMPLATE_TRANSFORMS, TemplateParser, splitClasses} from '@angular/compiler/src/template_parser/template_parser';
import {TEST_COMPILER_PROVIDERS} from '@angular/compiler/testing/test_bindings';
import {SchemaMetadata, SecurityContext, Type} from '@angular/core';
import {SchemaMetadata, SecurityContext} from '@angular/core';
import {Console} from '@angular/core/src/console';
import {TestBed, inject} from '@angular/core/testing';
@ -257,8 +257,7 @@ export function main() {
});
});
describe(
'TemplateParser', () => {
describe('TemplateParser', () => {
beforeEach(() => {
TestBed.configureCompiler({providers: [TEST_COMPILER_PROVIDERS, MOCK_SCHEMA_REGISTRY]});
});
@ -330,6 +329,13 @@ export function main() {
]);
});
it('should parse dotted name bound properties', () => {
expect(humanizeTplAst(parse('<div [dot.name]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'dot.name', 'v', null]
]);
});
it('should normalize property names via the element schema', () => {
expect(humanizeTplAst(parse('<div [mappedAttr]="v">', []))).toEqual([
[ElementAst, 'div'],
@ -365,21 +371,6 @@ export function main() {
]);
});
it('should report invalid prefixes', () => {
expect(() => parse('<p [atTr.foo]>', []))
.toThrowError(
`Template parse errors:\nInvalid property name 'atTr.foo' ("<p [ERROR ->][atTr.foo]>"): TestComp@0:3`);
expect(() => parse('<p [sTyle.foo]>', []))
.toThrowError(
`Template parse errors:\nInvalid property name 'sTyle.foo' ("<p [ERROR ->][sTyle.foo]>"): TestComp@0:3`);
expect(() => parse('<p [Class.foo]>', []))
.toThrowError(
`Template parse errors:\nInvalid property name 'Class.foo' ("<p [ERROR ->][Class.foo]>"): TestComp@0:3`);
expect(() => parse('<p [bar.foo]>', []))
.toThrowError(
`Template parse errors:\nInvalid property name 'bar.foo' ("<p [ERROR ->][bar.foo]>"): TestComp@0:3`);
});
describe('errors', () => {
it('should throw error when binding to an unknown property', () => {
expect(() => parse('<my-component [invalidProp]="bar"></my-component>', []))
@ -397,10 +388,8 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
2. If 'unknown' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<unknown></unknown>"): TestComp@0:0`);
});
it('should throw error when binding to an unknown custom element w/o bindings',
() => {
expect(() => parse('<un-known></un-known>', []))
.toThrowError(`Template parse errors:
it('should throw error when binding to an unknown custom element w/o bindings', () => {
expect(() => parse('<un-known></un-known>', [])).toThrowError(`Template parse errors:
'un-known' is not a known element:
1. If 'un-known' is an Angular component, then verify that it is part of this module.
2. If 'un-known' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<un-known></un-known>"): TestComp@0:0`);
@ -433,20 +422,16 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
]);
});
it('should parse bound properties via {{...}} and not report them as attributes',
() => {
it('should parse bound properties via {{...}} and not report them as attributes', () => {
expect(humanizeTplAst(parse('<div prop="{{v}}">', []))).toEqual([
[ElementAst, 'div'],
[
BoundElementPropertyAst, PropertyBindingType.Property, 'prop', '{{ v }}', null
]
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', '{{ v }}', null]
]);
});
it('should parse bound properties via bind-animate- and not report them as attributes',
() => {
expect(
humanizeTplAst(parse('<div bind-animate-someAnimation="value2">', [], [], [])))
expect(humanizeTplAst(parse('<div bind-animate-someAnimation="value2">', [], [], [])))
.toEqual([
[ElementAst, 'div'],
[
@ -565,12 +550,12 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
it('should allow events on explicit embedded templates that are emitted by a directive',
() => {
const dirA = CompileDirectiveMetadata
const dirA =
CompileDirectiveMetadata
.create({
selector: 'template',
outputs: ['e'],
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'DirA'}})
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}})
})
.toSummary();
expect(humanizeTplAst(parse('<template (e)="f"></template>', [dirA]))).toEqual([
@ -605,31 +590,31 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
describe('directives', () => {
it('should order directives by the directives array in the View and match them only once',
() => {
const dirA = CompileDirectiveMetadata
const dirA =
CompileDirectiveMetadata
.create({
selector: '[a]',
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'DirA'}})
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}})
})
.toSummary();
const dirB = CompileDirectiveMetadata
const dirB =
CompileDirectiveMetadata
.create({
selector: '[b]',
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'DirB'}})
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirB'}})
})
.toSummary();
const dirC = CompileDirectiveMetadata
const dirC =
CompileDirectiveMetadata
.create({
selector: '[c]',
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'DirC'}})
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirC'}})
})
.toSummary();
expect(humanizeTplAst(parse('<div a c b a b>', [dirA, dirB, dirC]))).toEqual([
[ElementAst, 'div'], [AttrAst, 'a', ''], [AttrAst, 'c', ''], [AttrAst, 'b', ''],
[AttrAst, 'a', ''], [AttrAst, 'b', ''], [DirectiveAst, dirA],
[DirectiveAst, dirB], [DirectiveAst, dirC]
[AttrAst, 'a', ''], [AttrAst, 'b', ''], [DirectiveAst, dirA], [DirectiveAst, dirB],
[DirectiveAst, dirC]
]);
});
@ -723,8 +708,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
})
.toSummary();
expect(humanizeTplAst(parse('<div [a]="expr"></div>', [dirA]))).toEqual([
[ElementAst, 'div'], [DirectiveAst, dirA],
[BoundDirectivePropertyAst, 'b', 'expr']
[ElementAst, 'div'], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'b', 'expr']
]);
});
@ -830,8 +814,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
}
function createDir(
selector: string,
{providers = null, viewProviders = null, deps = [], queries = []}: {
selector: string, {providers = null, viewProviders = null, deps = [], queries = []}: {
providers?: CompileProviderMetadata[],
viewProviders?: CompileProviderMetadata[],
deps?: string[],
@ -991,8 +974,7 @@ Binding to attribute 'onEvent' is disallowed for security reasons ("<my-componen
it('should mark directives and dependencies of directives as eager', () => {
const provider0 = createProvider('service0');
const provider1 = createProvider('service1');
const dirA =
createDir('[dirA]', {providers: [provider0, provider1], deps: ['service0']});
const dirA = createDir('[dirA]', {providers: [provider0, provider1], deps: ['service0']});
const elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0];
expect(elAst.providers.length).toBe(3);
expect(elAst.providers[0].providers).toEqual([provider0]);
@ -1258,34 +1240,33 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
describe('directives', () => {
it('should locate directives in property bindings', () => {
const dirA = CompileDirectiveMetadata
const dirA =
CompileDirectiveMetadata
.create({
selector: '[a=b]',
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'DirA'}}),
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}}),
inputs: ['a']
})
.toSummary();
const dirB = CompileDirectiveMetadata
const dirB =
CompileDirectiveMetadata
.create({
selector: '[b]',
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'DirB'}})
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirB'}})
})
.toSummary();
expect(humanizeTplAst(parse('<div template="a b" b>', [dirA, dirB]))).toEqual([
[EmbeddedTemplateAst], [DirectiveAst, dirA],
[BoundDirectivePropertyAst, 'a', 'b'], [ElementAst, 'div'], [AttrAst, 'b', ''],
[DirectiveAst, dirB]
[EmbeddedTemplateAst], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'a', 'b'],
[ElementAst, 'div'], [AttrAst, 'b', ''], [DirectiveAst, dirB]
]);
});
it('should not locate directives in variables', () => {
const dirA = CompileDirectiveMetadata
const dirA =
CompileDirectiveMetadata
.create({
selector: '[a]',
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'DirA'}})
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}})
})
.toSummary();
expect(humanizeTplAst(parse('<div template="let a=b">', [dirA]))).toEqual([
@ -1294,11 +1275,11 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
});
it('should not locate directives in references', () => {
const dirA = CompileDirectiveMetadata
const dirA =
CompileDirectiveMetadata
.create({
selector: '[a]',
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'DirA'}})
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}})
})
.toSummary();
expect(humanizeTplAst(parse('<div ref-a>', [dirA]))).toEqual([
@ -1328,8 +1309,7 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
let compCounter: number;
beforeEach(() => { compCounter = 0; });
function createComp(
selector: string, ngContentSelectors: string[]): CompileDirectiveSummary {
function createComp(selector: string, ngContentSelectors: string[]): CompileDirectiveSummary {
return CompileDirectiveMetadata
.create({
selector: selector,
@ -1353,9 +1333,8 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
describe('project text nodes', () => {
it('should project text nodes with wildcard selector', () => {
expect(humanizeContentProjection(parse('<div>hello</div>', [
createComp('div', ['*'])
]))).toEqual([['div', null], ['#text(hello)', 0]]);
expect(humanizeContentProjection(parse('<div>hello</div>', [createComp('div', ['*'])])))
.toEqual([['div', null], ['#text(hello)', 0]]);
});
});
@ -1428,10 +1407,9 @@ Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>
});
it('should project children of components with ngNonBindable', () => {
expect(
humanizeContentProjection(parse(
'<div ngNonBindable>{{hello}}<span></span></div>', [createComp('div', ['*'])])))
.toEqual([['div', null], ['#text({{hello}})', 0], ['span', 0]]);
expect(humanizeContentProjection(parse('<div ngNonBindable>{{hello}}<span></span></div>', [
createComp('div', ['*'])
]))).toEqual([['div', null], ['#text({{hello}})', 0], ['span', 0]]);
});
it('should match the element when there is an inline template', () => {
@ -1510,8 +1488,7 @@ Can't have multiple template bindings on one element. Use only one attribute nam
});
it('should report invalid property names', () => {
expect(() => parse('<div [invalidProp]></div>', []))
.toThrowError(`Template parse errors:
expect(() => parse('<div [invalidProp]></div>', [])).toThrowError(`Template parse errors:
Can't bind to 'invalidProp' since it isn't a known property of 'div'. ("<div [ERROR ->][invalidProp]></div>"): TestComp@0:5`);
});
@ -1655,8 +1632,7 @@ Property binding a not used by any directive on an embedded template. Make sure
});
it('should keep nested children of elements with ngNonBindable', () => {
expect(humanizeTplAst(parse('<div ngNonBindable><span>{{b}}</span></div>', [])))
.toEqual([
expect(humanizeTplAst(parse('<div ngNonBindable><span>{{b}}</span></div>', []))).toEqual([
[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [ElementAst, 'span'],
[TextAst, '{{b}}']
]);
@ -1680,11 +1656,10 @@ Property binding a not used by any directive on an embedded template. Make sure
it('should convert <ng-content> elements into regular elements inside of elements with ngNonBindable',
() => {
expect(
humanizeTplAst(parse('<div ngNonBindable><ng-content></ng-content>a</div>', [])))
expect(humanizeTplAst(parse('<div ngNonBindable><ng-content></ng-content>a</div>', [])))
.toEqual([
[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''],
[ElementAst, 'ng-content'], [TextAst, 'a']
[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [ElementAst, 'ng-content'],
[TextAst, 'a']
]);
});
@ -1717,10 +1692,8 @@ Property binding a not used by any directive on an embedded template. Make sure
});
it('should support variables', () => {
expect(humanizeTplAstSourceSpans(parse('<template let-a="b"></template>', [])))
.toEqual([
[EmbeddedTemplateAst, '<template let-a="b">'],
[VariableAst, 'a', 'b', 'let-a="b"']
expect(humanizeTplAstSourceSpans(parse('<template let-a="b"></template>', []))).toEqual([
[EmbeddedTemplateAst, '<template let-a="b">'], [VariableAst, 'a', 'b', 'let-a="b"']
]);
});
@ -1769,8 +1742,8 @@ Property binding a not used by any directive on an embedded template. Make sure
})
.toSummary();
expect(humanizeTplAstSourceSpans(parse('<div a>', [dirA, comp]))).toEqual([
[ElementAst, 'div', '<div a>'], [AttrAst, 'a', '', 'a'],
[DirectiveAst, dirA, '<div a>'], [DirectiveAst, comp, '<div a>']
[ElementAst, 'div', '<div a>'], [AttrAst, 'a', '', 'a'], [DirectiveAst, dirA, '<div a>'],
[DirectiveAst, comp, '<div a>']
]);
});
@ -1782,11 +1755,11 @@ Property binding a not used by any directive on an embedded template. Make sure
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'elDir'}})
})
.toSummary();
const attrSel = CompileDirectiveMetadata
const attrSel =
CompileDirectiveMetadata
.create({
selector: '[href]',
type: createTypeMeta(
{reference: {filePath: someModuleUrl, name: 'attrDir'}})
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'attrDir'}})
})
.toSummary();
@ -1812,8 +1785,7 @@ Property binding a not used by any directive on an embedded template. Make sure
})
.toSummary();
expect(humanizeTplAstSourceSpans(parse('<div [aProp]="foo"></div>', [dirA]))).toEqual([
[ElementAst, 'div', '<div [aProp]="foo">'],
[DirectiveAst, dirA, '<div [aProp]="foo">'],
[ElementAst, 'div', '<div [aProp]="foo">'], [DirectiveAst, dirA, '<div [aProp]="foo">'],
[BoundDirectivePropertyAst, 'aProp', 'foo', '[aProp]="foo"']
]);
});
@ -1880,8 +1852,8 @@ The pipe 'test' could not be found ("[ERROR ->]{{a | test}}"): TestComp@0:0`);
'<template ngPluralCase="many">big</template>' +
'</ng-container>';
expect(humanizeTplAst(parse(shortForm, [
]))).toEqual(humanizeTplAst(parse(expandedForm, [])));
expect(humanizeTplAst(parse(shortForm, []))).toEqual(humanizeTplAst(parse(expandedForm, [
])));
});
it('should expand select messages', () => {
@ -1891,8 +1863,8 @@ The pipe 'test' could not be found ("[ERROR ->]{{a | test}}"): TestComp@0:0`);
'<template ngSwitchDefault>bar</template>' +
'</ng-container>';
expect(humanizeTplAst(parse(shortForm, [
]))).toEqual(humanizeTplAst(parse(expandedForm, [])));
expect(humanizeTplAst(parse(shortForm, []))).toEqual(humanizeTplAst(parse(expandedForm, [
])));
});
it('should be possible to escape ICU messages', () => {