Skip to content

Commit

Permalink
fix(language-service): expression bindings should not break directive…
Browse files Browse the repository at this point in the history
… matching

The language service uses an elements attributes to determine if it
matches a directive in the component scope. We do this by accumulating
all attribute bindings and matching against the selectors for the
available directives. When an attibute has a complex (non-literal
primitive) value, this code would previously generate an invalid
attribute such as `[attrName='1' + '2']`. For cases where the attribute
is bound to an expression that is not a literal primitive, this commit
changes the logic to only generate the attribute name and exclude the
value.

Fixes angular/vscode-ng-language-service#1278
  • Loading branch information
atscott committed Apr 13, 2021
1 parent c9aa87c commit 1f116be
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
9 changes: 9 additions & 0 deletions packages/language-service/ivy/test/quick_info_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ describe('quick info', () => {
expect(toText(documentation)).toBe('This Component provides the `test-comp` selector.');
});

it('should work for components when there is an expression in a binding', () => {
const {documentation} = expectQuickInfo({
templateOverride: `<t¦est-comp [attr.id]="'1' + '2'" [attr.name]="'myName'"></test-comp>`,
expectedSpanText: `<test-comp [attr.id]="'1' + '2'" [attr.name]="'myName'"></test-comp>`,
expectedDisplayString: '(component) AppModule.TestComponent'
});
expect(toText(documentation)).toBe('This Component provides the `test-comp` selector.');
});

it('should work for structural directives', () => {
const {documentation} = expectQuickInfo({
templateOverride: `<div *¦ngFor="let item of heroes"></div>`,
Expand Down
7 changes: 6 additions & 1 deletion packages/language-service/ivy/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,12 @@ function getFirstComponentForTemplateFile(fileName: string, compiler: NgCompiler
* Given an attribute node, converts it to string form.
*/
function toAttributeString(attribute: t.TextAttribute|t.BoundAttribute|t.BoundEvent): string {
if (attribute instanceof t.BoundEvent) {
if (attribute instanceof t.BoundEvent ||
// When the expressio in the attribute binding is not a literal primitive, fall back to using
// just the attribute name. Non-literals can result in invalid HTML such as
// `[attrName='1'+'2']`.
(attribute.value instanceof e.ASTWithSource &&
!(attribute.value.ast instanceof e.LiteralPrimitive))) {
return `[${attribute.name}]`;
} else {
return `[${attribute.name}=${attribute.valueSpan?.toString() ?? ''}]`;
Expand Down

0 comments on commit 1f116be

Please sign in to comment.