The main intention behind the new HTML template flow control syntax was to have a new basis for building new possibilities in the framework’s templates. The first new feature made possible by the syntax is the defer instruction, with which it is possible to lazy load components directly from the HTML template.
We learned in Chapter 2, Organizing Your Application, that the best practice is to separate your application into functionality modules and configure Angular to load these modules in a lazy way. This means that the module and its components would only be loaded if the user accessed a certain route, resulting in smaller bundles and better performance of your application, especially if your user does not have a good internet connection (such as 3G).
The defer command has the same purpose but instead of working for modules, it works for standalone components. We studied standalone components in Chapter 11, Micro Frontend with Angular Elements.
We will start our refactoring by transforming the exercise list components into a standalone component. In the diary.component.ts file, make the following changes:
@Component({
standalone: true,
templateUrl: ‘./diary.component.html’,
styleUrls: [‘./diary.component.css’],
imports: [ListEntriesComponent, NewItemButtonComponent],
})
In the preceding code, we have included the standalone attribute set to true and added the components it depends on directly using the imports attribute.
We will do the same procedure in the EntryItemComponent component:
@Component({
selector: ‘app-entry-item’,
standalone: true,
templateUrl: ‘./entry-item.component.html’,
styleUrls: [‘./entry-item.component.css’],
imports: [DatePipe],
})
In this component, in addition to the standalone property, we need to add the dependency so that the date pipe works. It is necessary to note that the standalone component needs to have its dependencies declaratively in the imports attribute, since it is not linked to any Angular module.
To lazy load the template, we will also convert the NewItemButtonComponent component into a standalone one:
@Component({
selector: ‘app-new-item-button’,
templateUrl: ‘./new-item-button.component.html’,
styleUrls: [‘./new-item-button.component.css’],
standalone: true,
})
The last component to be converted into a standalone component is ListEntriesComponent, changing it as follows:
@Component({
selector: ‘app-list-entries’,
standalone: true,
templateUrl: ‘./list-entries.component.html’,
styleUrls: [‘./list-entries.component.css’],
imports: [EntryItemComponent],
})
In this example, we added the EntryItemComponent dependency to the import attribute.
No Responses