Thursday, 15 November 2018

Top Angular 5 Best Practices 2018 Edition


When building an application within the specific framework, you need to know the best practices to write clean and maintainable code. We formed Top Angular 5 Best Practices based on our experience.
So, we invite you to get acquainted with the new features and use those practices in your work.

Angular 5 Best Practices: 5 Tips For Cleaner Code

 #1. Project structure

In app development, a smooth project structure is a point to pay attention in the first place. There is no completely defined way of building the perfect structure because everything depends on the work. Since requirements differ from project to project it is hard to find a universal structure for every case. Yet style guide gives us some hints in developing optimal application structure.
The best move is to start with the Angular CLI.
npm install -g @angular/cli
ng new my-project
The CLI is the easiest and fastest way to create a new project on Angular. It enables to deploy the project within a few minutes and develop sizeable apps too. But the main benefit of the CLI is the way of building automating pipeline in live development with ng serve and in production ng build -prod. Angular CLI makes it much easier to manage a project. But such simplicity can be translated into inflexibility. This works great for simple projects, but sizeable ones will need a manual approach.
Style guide suggests starting from the small parts, but keep in mind the final result and adjust the project structure respectively.  To provide consistent structure keep it small and easy to maintain. The structure should be suitable to evolve as the app expands.

 #2. Writing components

Components are not the new practice, but it is one of Angular’s a core feature, so we considered to mention it. When components are organized and reusable, it is already half work done. Try to be DRY, especially when you have repetitive templates in the application. Rather than pollute components with the same code, consider creating one or several base classes.
The angular application architecture is like a tree of сomponents. To build more maintainable and organized app, we suggest to classify components and try to make them reusable. This will provide a clear application structure and build unloaded with similar components code.
According to your needs, you can use Container (Smart) or Presentation (Dumb) Components. When you have the component passing properties down to other components, make it Smart.
export class ContactPageComponent
 
{

/* container component */

user$: Observable<User>;

constructor(route: ActivatedRoute) 
{

this.user$ = route.data

.map(({ user }) => user);
}

}
If there is a component that only performs dispatching actions, better define it as Presentation one.
export class ContactDetailComponent

 {

    /* presentation component */

    @Input() user: User;

}

#3. Performance

Angular is quite a fast framework. But due to project expansion, its performance may decrease. There are some ways you can help Angular to process faster. To start you can ChangeDetectionStrategy to onPush. It gives a signal to the Angular that the component only depends on his own Input. Thus, Angular will check it in two cases. When a component or its derivative caused the event or if the Input reference changes.
Data changes in the collection also can affect the performance. To deal with this issue, you can use trackBy function. It allows Angular track added/removed items in the collection by a unique identifier.
We couldn’t help but mention the strongest Angular feature – LazyLoading. It splits the app into modules and loading them on-demand, thus cutting load time.
{
  path: 'admin',
  loadChildren:
 'app/admin/admin.module',
}

#4. Use RxJS

RxJS is difficult for understanding. Yet it does its job and simplifies developer’s work. In fifth Angular edition, RxJS has undergone some minor changes. The code remained the same, but RxJS moved to lettable operators. It allowed cutting problems associated with the old mechanism of data import.
Also, developers managed to fix all shortcomings associated with splitting and tree shaking. RxJS library is a powerful tool that helps to optimal application logic and keeps code clean.

 #5. Testing

Angular 5 has an effective testing tool. Testing enables us to make sure that certain parts of the application work exactly as you expect them to. This to some extent saves the existing code from breakdowns, helps to clarify – how it will work in various cases. And, in the end, allows detecting code weaknesses.
We would like to describe the main aspects of testing in Angular 5. To simplify the testing process, choose test type that fits in your particular situation. Also, make sure you know all the capabilities of your IDE in terms of assisting in testing. And finally, you can disable checking the definition for directives and child components. To do so, in the TestBed configuration, write the NO_ERRORS_SCHEMA:
TestBed.configureTestingModule({

declarations: [ AppComponent ],

schemas: [ NO_ERRORS_SCHEMA ]

})
Also, important to mention TestBed alone. It is the utility for simplifying and facilitating a testing process in Angular. We can check whether the component was created, how it interacts with templates and dependencies.
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
Angular 5 Best practices are not intended to dictate an exclusive course of procedure to be followed or act like fixed protocol. It is rather recommendations on how to keep project simple and clean. But remember that development is a sphere where creativity pays not the last role.
@Component(
template: 
`<div *ngFor="var item in items; trackBy=customTrackBy"
>{{item}}</div>`
)
class MyCoponent {
customTrackBy
(index: number, obj: any): any {
return index;
}
}

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...