Skip to content

Commit 7f4022d

Browse files
committed
fix(migrations): Fix NgStyle migration
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 2e34924 commit 7f4022d

2 files changed

Lines changed: 41 additions & 5 deletions

File tree

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 (propertyIndex === 0) {
169+
return {start: property.getFullStart(), end: properties[1].getFullStart()};
172170
}
173171

174-
return {start: property.getStart(), end};
172+
if (properties.length === 1) {
173+
const sourceFile = property.getSourceFile();
174+
let end = property.getEnd();
175+
const textAfter = sourceFile.text.substring(end, parent.getEnd());
176+
const commaIndex = textAfter.indexOf(',');
177+
if (commaIndex !== -1) {
178+
end += commaIndex + 1;
179+
}
180+
return {start: property.getFullStart(), end};
181+
}
182+
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: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,33 @@ 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+
console.log('content ?> ', content);
407+
408+
expect(content).toContain(`@Component({
409+
template: \`<div [style.background]="'red'"></div>\`,
410+
})
411+
export class Cmp {}`);
412+
});
413+
387414
it('should migrate when NgStyle is provided by CommonModule', async () => {
388415
writeFile(
389416
'/app.component.ts',

0 commit comments

Comments
 (0)