Here I recommend my own backend management framework based on Angular Material

Making: github.com/ng-matero/n…

Preview address: ng-matero.github. IO /ng-matero/

Why Use Angular

I’m not an Angular evangelist, but now I call myself an Angular evangelist and get excited about working with Angular on projects. I have studied all the three major front-end frameworks, and there are relevant tutorials of the three in my blog. I first got to know React, but I have no actual project experience and only made some demos. I have done a complex mobile terminal big data project with Vue. The technical stack is Framework7 + Vue + Vuex, and the overall effect is satisfactory.

Because last year’s projects were almost all background management systems, framework was not used much, mainly in the traditional way of development, in order to improve the front-end development experience, gradually close to the framework. Compared with Bootstrap frameworks, most of them have Angular versions and the component libraries are the most comprehensive. React and Vue versions have relatively few component libraries. Developing large backend management systems with Angular has proven to have unique advantages. Angular, on the other hand, is the epitome of difficulty complexity, bringing together design patterns, design philosophies, engineering ideas, and a qualitative leap forward for front-end development. In addition, THE Angular documentation fascinates me. Besides the basic tutorials, the core knowledge is the most interesting part of the Angular documentation. It is not only a technical insider, but also a practical way to learn a lot of basic knowledge.

Angular development requires a lot of upfront knowledge of TypeScript, RxJS, etc., which makes it expensive to learn, which is another reason why many people are discouraged. After a long time of study and preparation, I finally had the opportunity to practice the project this year. The project is very small and an independent module of the whole system, but I have covered almost all the knowledge, which can be described as “a sparrow is small but has all the five organs”. This article is the summary and thinking of the project.

Setting up the development environment

Setting up the development environment is simple, and you can do almost everything with the Angular CLI, but you need to do some custom configuration when interfacing with the backend. Here are the basic Settings for the proxy.config.json file:

{
  "/api": {
    "target": "http://localhost:3000"."secure": false}}Copy the code

The Angular CLI is used throughout the project, from development to packaging, as part of Angular engineering. Because the CLI has many parameters, you must read the documentation carefully and set the parameters properly. Almost all requirements can be found in the parameters. If you use the ng build package, there may be a resource reference error. For example, if you use ng build package, there may be a resource reference error.

You may also encounter issues with transferring cookies when tuning interfaces, as shown in The Problem with Angular carrying cookies on cross-domain requests.

Select the UI library

Because the project was relatively small, I planned to write components, such as paging, at the beginning of the development, but the actual situation was complicated, especially when I just got to Angular, I still had a little confusion about component interaction and asynchronous data. I tried to write, but I still had a lot of problems, so I chose a mature UI library.

The choice of UI library depends on the style. For example, my project uses Bootstrap, so THE UI library uses NGX-Bootstrap, which is related to Bootstrap. For background management system, common components are nothing more than pop-ups, paging, tabs, etc. For more complex systems, you can also choose other UI libraries with richer components, such as PrimeNG, for your own use.

The component library mainly uses pop-ups and pagination, among which the popup of NGX-Bootstrap is an excellent component, which is used for information input and prompt. The following is a custom Alert popover, shared by Service components.

The code in modal-alert.component.html is the HTML structure of the entire component, with two variables and an instance method.

<div class="modal-header">
  <h4 class="modal-title pull-left">{{title}}</h4>
  <button type="button" class="close pull-right" aria-label="Close" (click) ="bsModalRef.hide()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  {{content}}
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-default" (click) ="bsModalRef.hide()">Shut down</button>
</div>
Copy the code

Define variables and component instances in modal-alert.component.ts.

import { Component, OnInit } from '@angular/core';

import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

@Component({
  selector: 'app-modal-alert'.templateUrl: './modal-alert.component.html'.styleUrls: ['./modal-alert.component.css']})export class ModalAlertComponent implements OnInit {

  title: string;
  content: string;
 
  constructor(public bsModalRef: BsModalRef) {}
 
  ngOnInit(){}}Copy the code

The component’s public method modalAlert() is defined in modal.service.ts.

export class ModalService {
  modalRef: BsModalRef;
 
  constructor(private modalService: BsModalService, private http: HttpClient){}modalAlert(msg: string) {
    const initialState = {
      content: msg,
      title: 'Prompt message'
    };
    this.modalRef = this.modalService.show(ModalAlertComponent,
      {
        initialState: initialState,
        class: 'modal-sm'}); }}Copy the code

Finally, you need to define entryComponents in app.module.ts, for example:

@NgModule({
  declarations: [...]. .imports: [...]. .entryComponents: [ModalAlertComponent, ModalConfirmComponent]
})
Copy the code

It is also important not to use the same name as the function when using a template reference variable, which is sometimes overlooked by diagram saving. For example, the following code will report an error:

<ng-template #Alert>.<div class="modal-footer">
    <button type="button" class="btn btn-primary" (click) ="Alert()">determine</button>
  </div>
</ng-template>
Copy the code

Diversity of forms

Angular provides two types of forms, template-driven and reactive. Template-driven forms are simple and flexible, and are suitable for uncomplicated form data.

For forms, we put Angular and Vue together and say that Vue’s form bindings are template-driven forms. Angular’s template-driven forms don’t have checkbox bindings, so if you need one, you can choose a more flexible and powerful reactive form for data binding. In fact, you can use the natural select checkbox for array data. For example:

<div class="form-group">
  <label for="power">Hero Power</label>
  <select class="form-control"  id="power"
          multiple
          required
          [(ngModel)] ="model.power" 
          name="power">
    <option *ngFor="let pow of powers" [value] ="pow">{{pow}}</option>
  </select>
</div>
Copy the code

For array type data, there are two binding methods in Vue, check boxes and select checkboxes. Whereas the value of a check box can only be true or false, the value of a select checkbox is an array. So Vue handles checkbox multiselection, which Angular doesn’t, and you need to handle it yourself. This is easy to implement with Angular’s reactive forms. However, template-driven forms can be implemented in an alternative way, such as manually implementing a two-way data binding, which is cumbersome but feasible. I’ll cover this topic in the next article.

The official documentation on forms is very detailed, and from user input to binding to validation, two-way data binding can be easily implemented. I love the [()] (banana in a box) data binding approach in Angular, and have learned a lot about two-way data binding by reading the core of the official documentation.

Data mapping for pipes

Pipes are very useful, and in my opinion, time shifting and data mapping are common. I mainly want to talk about data mapping. At first, I planned to write my own pipe about data mapping, but then I thought, should different data mapping write a pipe separately? Then I wondered if there was a built-in pipe for data mapping, looked through the documentation, and finally found I18nPluralPipe for data mapping. Let’s use one of the most common data mapping examples, such as saving gender data with 1 for male and 2 for female.

@Component({
  selector: 'i18n-plural-pipe'.template: `<div>{{ sex | i18nPlural: sexMapping }}</div>`
})
export class I18nPluralPipeComponent {
  sex: string = '1';
  sexMapping: {[k: string] :string} = {'= 1': 'male'.'= 2': 'woman'.'other': 'other'};
}
Copy the code

I18nPluralPipe uses the ICU format, which is quite an insight. This pipe works really well, at least without having to write a dedicated pipe for every data map.

In the sample code above, sexMapping is defined using indexable types in the interface.

RxJS for asynchronous development

RxJS is a complicated topic that I don’t fully understand. The Angular official website defines it as follows:

Responsive programming is an asynchronous programming paradigm for data flow and change propagation (Wikipedia). RxJS (Responsive Extension JavaScript version) is a library for responsive programming using observables that makes it easier to combine asynchronous code with callback-based code (RxJS Docs).

There are a lot of things you can say about the history of asynchronous development, such as callbacks, promises, iterators and generators, async and await, and observables in RxJS should be the next more powerful asynchronous programming method. The Angular website compares observables to promises.

Note that only when an Observable subscribes to an instance does it start publishing values. To subscribe, the instance’s subscribe() method is called and an observer object is passed to it to receive notifications. When I first started using it, I was cheated for this reason. Here is a very simple official example:

import { ajax } from 'rxjs/ajax';

// Create an Observable that sends AJAX requests
const apiData = ajax('/api/data');
// Subscribe request
apiData.subscribe(res= > console.log(res.status, res.response));
Copy the code

conclusion

This simple little project took about a week to get started with Angular, and there’s a lot more to learn about Angular. Overall, Angular + TypeScript development is very comfortable, VSCode supports TS perfectly, syntax hints, autocompletion, and strongly typed languages are the trend of front-end development. Developing with Angular, as I mentioned at the beginning of this article, is not just about learning a framework, it’s about learning an idea. Learning about better development models, open source projects, keeps me on the cutting edge of technology, and that’s what I learned the most.

If you like Angular or are interested in Angular Material, welcome to the group discussion!