I had the honor to attend ngChina2018 developer conference and listened to will share Angular development tips. I have been in touch with Angular for almost a year, so I decided to make a summary of some tips in Angular development.

Tool post

As the saying goes, “If you want to do a good job, you must first sharpen your tools.” Here’s how to sharpen VS Code’s tools.

  1. Ditch Explorer and use the shortcut Commd + P to find documents, which by default shows recently opened documents and supports fuzzy search of files

  2. Quickly open a recent document: Forward Ctrl+➕ Back Ctrl+➖

  3. Use THE VS Code refactoring feature flexibly, using the Command + shortcut to refactor Code

  4. Install the Angular Extension Pack, which integrates plugins to make Angular development more efficient, such as:

    Quick use of Angular components and directives (Angular V7 Snippets). Use 'ng-*' to generate common ng code Snippets. Create Component, Directive, etc. (Angular Snippets)Copy the code

    Convert JSON to class TS using shortcut keys

    Ctrl+Alt+V converts JSON from the stickboard to Typescript. Ctrl+Alt+S generates Typescript from the selected JSONCopy the code

    Another useful feature worth mentioning is the ability to quickly switch between components using shortcuts (Angular2-switcher).

    There are many other features detailed in the ‘Angular Extension Pack’ plugin

  5. Install Clipboard History, which stores your most recent copy records, making it easy to record and paste the last few copies

  6. Install the plug-in Local History, which maintains a Local History of files. Every time modify the file, will retain a copy of the old content in local history, you can always will file with the history of any old version comparison, in the event of accident, can help us to restore the missing content, it is important to note. It produces a history folder for the backup of local modification, So we need to exclude the.gitignore folder to avoid committing it to the Git repository.

  7. Prettier-code Formatter prettier-code Formatter Prettier-code Formatter Prettier-code Formatter Prettier-Code Formatter Prettier-Code Formatter

  8. Angular Angury is a Chrome plugin that allows you to view Component State, Router Tree, and NgModules. Angular Angury is not particularly useful for complex projects, including dynamic components. But in some simple projects, or novice when learning to install this plug-in is more convenient debugging and troubleshooting)

Development of article

Here are some tips for Angular developmentCopy the code
  1. Use template language AS, use AS to rename some attributes with deep nested structure before improvement:

    <div *ngFor="let queue of fileUploadQueues">
        <div class="icon" *ngIf="queue.result.file.icon">{{ queue.result.file.icon }}</div>
        <div class="name" *ngIf="queue.result.file.name">{{ queue.result.file.name }}</div>
        <div class="size" *ngIf="queue.result.file.size">{{ queue.result.file.size }}</div>
    </div>
    Copy the code

    After the improvement:

    <div *ngFor="let queue of fileUploadQueues">
      <ng-container *ngIf="queue.result.file as file">
           <div class="icon" *ngIf="file.icon">{{ file.icon }}</div>
           <div class="name" *ngIf="file.name">{{ file.name }}</div>
           <div class="size" *ngIf="file.size">{{ file.size }}</div>
      </ng-container>
    </div>
    Copy the code
  2. Use *ngIfElse flexibly. Many people write *ngIf all the time and don’t know that Angular supports the else *ngIf=” condition; Else template “, look at the following two pieces of code

    Before improvement:

    <div *ngIf="(data$ | async).length > 0">... </div> <div *ngIf=! "" (data$ | async).length > 0"> No data </div>Copy the code

    After the improvement:

    <div *ngIf="(data$ | async).length > 0; else emptyTemplate;">... </div> <ng-template#emptyTemplate>No data </ng-template>Copy the code

    The same effect can be achieved with the improved method, but since the data is subscribed via async, the first method is equivalent to two subscriptions. Of course, it can also be solved with as. Here is just an example. In another case, when there are many conditions, if you write in the first way, if there are changes to the conditions, you must maintain the reversed conditions, but in the ngIfElse way, you only need to maintain once.

  3. Ng-container is used to clean up codes to make them clearer and more readable

    <ng-container *ngIf="type === 1">... </ng-container> <ng-container *ngIf="type === 2">... </ng-container> <ng-container *ngIf="type === 3">... </ng-container>Copy the code
  4. @viewChild reads an instance of the specified type

    <input #input thyInput [thyAutofocus]="true" />
    Copy the code

    The above line has three instances: ElementRef, ThyInputComponent, and ThyAutoFocusDirective. What do we do in some cases if we want to get an instance of the specified type?

    @ViewChild('input', { read:ThyInputComponent })  inputComponent : ThyInputComponent ;
    Copy the code
  5. Using the Async pipeline, subscribe to streams directly in the template rather than storing the results in intermediate properties, and Angular will automatically unsubscribe when the component is destroyed.

    <div *ngFor="let item of data$ | async">... </div>Copy the code

    In some cases, we may need to reuse the subscribed data, but we can’t subscribe with async every time we use it, so we can rename it with as alignment.

    <div *ngFor="let item of data$ | async as data"</span> </div>Copy the code
  6. In some complex businesses, we may need to subscribe to multiple streams, and unsubscribing one by one is tedious and creates a lot of redundant code, which is not conducive to the maintenance of the code. At this point we can takeUntil to manage multiple subscriptions and unsubscribe.

    private _ngUnsubscribe$ = new Subject();
    
    ngOnInit() {
     this.students$.pipe(
        takeUntil(_ngUnsubscribe$)
     ).subscribe(() => {
             ...
     });
     this.books$.pipe(
        takeUntil(_ngUnsubscribe$)
     ).subscribe(() => {
             ...
     });
    }
    ngOnDestroy() {
      this._ngUnsubscribe$.next();
      this._ngUnsubscribe$.complete();
    }
    Copy the code
  7. We know that Angular handles change detection automatically because it uses zone.js, which is simply patched to block browser events. Change detection is then performed, but change detection is extremely resource-intensive and can cause performance problems if a large number of events are bound, so we can use runOutsideAngular to reduce unnecessary change detection.

    this.ngZone.runOutsideAngular(() => {
       this.renderer.listen(this.elementRef.nativeElement, 'keydown', event => {
          const keyCode = event.which || event.keyCode;
             if(keyCode === keycodes.ENTER) { event.preventDefault(); this.ngZone.run(() => { this.thyEnter.emit(event); }); }}); });Copy the code

    The above code binds a carriage return event. If runOutsideAngular is not used, the change detection will be performed as soon as the keyboard input event is triggered. In this case, we can use runOutsideAngular when only the enter event is used. Call ngzone.run () to actively trigger change detection

  8. Be flexible with ngTemplateOutlet for recursion

    <ng-container *ngFor="let node of treeNodes;" [ngTemplateOutlet]="nodeTemplate" 
             [ngTemplateOutletContext]="{node: node}">
    </ng-container>
    
    <ng-template #nodeTemplate let-node="node">
         <div class='title'>{{node.title}}</div>
          <ng-container *ngFor="let child of node? .children;"  [ngTemplateOutlet]="nodeTemplate"
                         [ngTemplateOutletContext]="{node: child}">
           </ng-container>
    </ng-template>
    Copy the code

    If the business scenario is simple, we can use Angular ngTemplateOutlet to recursively display the data. If the business scenario is complex, we recommend using components.

Write in the last

Here are some tips I’ve accumulated over the course of Angular development. If you find any mistakes, please correct them. In fact, I wrote this article last year, but I always feel that there is something wrong with it, but it doesn’t matter


Worktile’s website: Worktile.com

Author: Wang Kai

This article was first published on Worktile’s official blog.