Skip to content

Commit 404d810

Browse files
author
Rishabhdeep Singh
committed
fix(migrations): fix NgClass leaving trailing comma after removal
This fixes an issue where when removing NgClass from the imports array of a component, an extra trailing comma would be left behind if it was the last element.
1 parent ada150c commit 404d810

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

packages/core/schematics/ng-generate/ngclass-to-class-migration/util.ts

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

179179
const properties = parent.properties;
180180
const propertyIndex = properties.indexOf(property);
181-
const end = property.getEnd();
182181

183-
if (propertyIndex < properties.length - 1) {
184-
const nextProperty = properties[propertyIndex + 1];
185-
return {start: property.getStart(), end: nextProperty.getStart()};
182+
if (propertyIndex === 0) {
183+
return {start: property.getFullStart(), end: properties[1].getFullStart()};
186184
}
187185

188-
return {start: property.getStart(), end};
186+
if (properties.length === 1) {
187+
const sourceFile = property.getSourceFile();
188+
let end = property.getEnd();
189+
const textAfter = sourceFile.text.substring(end, parent.getEnd());
190+
const commaIndex = textAfter.indexOf(',');
191+
if (commaIndex !== -1) {
192+
end += commaIndex + 1;
193+
}
194+
return {start: property.getFullStart(), end};
195+
}
196+
197+
return {start: properties[propertyIndex - 1].getEnd(), end: property.getEnd()};
189198
}
190199

191200
export function calculateImportReplacements(

packages/core/schematics/test/ngclass_to_class_migration_spec.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,31 @@ describe('NgClass migration', () => {
519519
expect(content).not.toContain('imports: [NgFor, NgIf,]'); // No trailing comma
520520
});
521521

522+
it('should handle multiline imports array formatting with NgClass at the end', async () => {
523+
writeFile(
524+
'/app.component.ts',
525+
`
526+
import {Component} from '@angular/core';
527+
import {NgClass} from '@angular/common';
528+
529+
@Component({
530+
template: \`<div [ngClass]="{'admin': isAdmin}"></div>\`,
531+
imports: [NgClass],
532+
})
533+
export class Cmp {}
534+
`,
535+
);
536+
537+
await runMigration();
538+
539+
const content = tree.readContent('/app.component.ts');
540+
541+
expect(content).toContain(`@Component({
542+
template: \`<div [class.admin]="isAdmin"></div>\`,
543+
})
544+
export class Cmp {}`);
545+
});
546+
522547
it('should handle multiline imports array formatting', async () => {
523548
writeFile(
524549
'/app.component.ts',

0 commit comments

Comments
 (0)