As you know in angular 17 we can have different syntax for ngIf
, ngFor
and so on. Am looking for an efficient way of migrating old syntax in html files to the new on presented in Angular 17:
For example I had this old html in angular 15:
<ng-container *ngIf="!dynamicWidth; else FlexibleRef">
<div class="c-title"></div>
<div class="c-desc c-desc__short"></div>
<div class="c-desc c-desc__long"></div>
</ng-container>
<ng-template #FlexibleRef>
<div
*ngFor="let item of count | numberRange; let i = index"
[ngStyle]="{ width: (100 / count) * (i + 1) + '%' }"
class="flexible-desc"></div>
</ng-template>
And need it in the new syntax like this:
@if (!dynamicWidth) {
<div class="c-title"></div>
<div class="c-desc c-desc__short"></div>
<div class="c-desc c-desc__long"></div>
} @else {
@for (item of count | numberRange; track item; let i = $index) {
<div [ngStyle]="{ width: (100 / count) * (i + 1) + '%' }" class="flexible-desc">. </div>
}
}
2
Answers
Angular provides with v17 an optional schematics to migrate directive based templates to control flow :
If you’re using the Angular CLI, you can run
ng g @angular/core:control-flow
If using Nx, you can run
nx generate @angular/core:control-flow-migration
When you run either of these, the CLI will ask you which path in your project should be migrated. By default, it will apply to
./
, which will migrate your whole project. You can give it a path to a particular directory, component, etc.At work, I own a collection of features in a certain directory of a Nx monorepo. To migrate my section, I used
./libs/project-name/my-directory-name
and it ran against all of feature/ui libs I own there. You can also specify the path all the way down to the template if you want and perform the migration file by file. It even works for template literals defined in the component decorator.