Skip to content

Commit 730684b

Browse files
aparzimattrbeck
authored andcommitted
fix(migrations): prevent trailing comma syntax errors after removing NgStyle
This fixes an issue where when removing NgStyle from the imports array of a component, an extra trailing comma would be left behind if it was the last element in that component`.
1 parent 83032e3 commit 730684b

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

packages/core/schematics/ng-generate/ngstyle-to-style-migration/util.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -164,14 +164,23 @@ function getPropertyRemovalRange(property: ts.ObjectLiteralElementLike): {
164164

165165
const properties = parent.properties;
166166
const propertyIndex = properties.indexOf(property);
167-
const end = property.getEnd();
168167

169-
if (propertyIndex < properties.length - 1) {
170-
const nextProperty = properties[propertyIndex + 1];
171-
return {start: property.getStart(), end: nextProperty.getStart()};
168+
if (properties.length === 1) {
169+
const sourceFile = property.getSourceFile();
170+
let end = property.getEnd();
171+
const textAfter = sourceFile.text.substring(end, parent.getEnd());
172+
const commaIndex = textAfter.indexOf(',');
173+
if (commaIndex !== -1) {
174+
end += commaIndex + 1;
175+
}
176+
return {start: property.getFullStart(), end};
177+
}
178+
179+
if (propertyIndex === 0) {
180+
return {start: property.getFullStart(), end: properties[1].getFullStart()};
172181
}
173182

174-
return {start: property.getStart(), end};
183+
return {start: properties[propertyIndex - 1].getEnd(), end: property.getEnd()};
175184
}
176185

177186
export function calculateImportReplacements(

packages/core/schematics/test/ngstyle_to_style_migration_spec.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,31 @@ describe('NgStyle migration', () => {
384384
export class Cmp {}`);
385385
});
386386

387+
it('should handle multiline imports array formatting with NgStyle at the end', async () => {
388+
writeFile(
389+
'/app.component.ts',
390+
`
391+
import {Component} from '@angular/core';
392+
import {NgStyle} from '@angular/common';
393+
394+
@Component({
395+
template: \`<div [ngStyle]="{'background': 'red'}"></div>\`,
396+
imports: [NgStyle],
397+
})
398+
export class Cmp {}
399+
`,
400+
);
401+
402+
await runMigration();
403+
404+
const content = tree.readContent('/app.component.ts');
405+
406+
expect(content).toContain(`@Component({
407+
template: \`<div [style.background]="'red'"></div>\`,
408+
})
409+
export class Cmp {}`);
410+
});
411+
387412
it('should migrate when NgStyle is provided by CommonModule', async () => {
388413
writeFile(
389414
'/app.component.ts',

0 commit comments

Comments
 (0)