Learn the easiest Angular2 tutorial ever

Author: Wang Peng [email protected]

Section 1: Angular 2.0 from 0 to 1 (I) Section 2: Angular 2.0 from 0 to 1 (II) Section 3: Angular 2.0 from 0 to 1 (III) Section 4: Angular 2.0 from 0 to 1 (IV) Section 5: Angular 2.0 from 0 to 1 (IV) Angular 2.0 from 0 to 1 (5) Section 6: Angular 2.0 from 0 to 1 (6)

Section 1: Get to know Angular 2.0

preface

Angular 2 is a cross-platform, all-terminal framework from Google that has the following advantages over React and Vue.

  1. Since Google’s goal is to deliver a complete solution, the official default libraries (such as routing, HTTP, dependency injection (DI), etc.) are complete without having to choose from them. React’s big pain point is that too many options lead to too much effort in the configuration process of finding components and libraries. On the other hand, this is also its advantage.
  2. Official support for TypeScript (Microsoft’s strongly typed version of JavaScript) as the preferred programming language makes the problems of developing scripting languages easier to find earlier.
  3. Rxjs-friendly makes responsive programming in Augular2 extremely easy (the Google framework relies on so many Microsoft products, so Microsoft’s transition has been successful).
  4. Support NativeScript and Even ReactNative Android/iOS app development (ReactNative)
  5. Support for server-side rendering (React also supports)

But in general, I think Angular2 is more suitable for programmers who transition from native App development or backend Java/.Net to front-end development, because its development model is closer to that of traditional strongly typed languages, plus the official built-in components and class libraries are more complete, there is an official Chinese site, and the learning curve is lower. For those of you who have experience with Angular 1.x development, note that 2.x and 1.x are completely different, even though there is only one version number difference. Don’t expect 1.x apps to migrate smoothly to 2.x.

Environment Configuration Requirements

Angular2 requires node.js and NPM. Our example requires node.js 6.x.x and NPM 3.x.x. Use node -v and NPM -v to check. For well-known reasons, the nPMjs.org site is often not very smooth, here is a domestic mirror maintained by the Taobao team, npm.taobao.org/. After installed the node, please enter the NPM config set registry at https://registry.npm.taobao.org

Instead of using the examples given in the official Quick Start documentation, we will use a tool currently under development by the Angular team, the Angular CLI. This is a command-line tool similar to the React CLI and Ember CLI for quickly building Angular2 applications. Its advantages include further masking of many configuration steps, automatic organization of code according to official recommended patterns, automatic generation of templates such as components/services, and easier distribution and testing of code. Since the tool is still in beta, use the NPM install -g angular-cli@latest command to install it.

There are also many IDE options, including Free Visual Studio Code and Atom, and WebStorm. Visual Studio Code is recommended and can be downloaded for Windows/Linux/MacOS at code.visualStudio.com/.

With these tools installed and the development environment in place, we’re ready to explore Angular2.

The first little app is Hello Angular

Now open a terminal and type ng new hello-angular




C1_s1_ng_new_hello – presents. PNG – 51.7 kB

As you can see above, this command creates a new project named “hello-angular.” Go to the project directory and type code. You can open the IDE and see the following directory




C1_s1_vscode_project_struct. PNG – 300.1 kB

. | – editorconfig / / general editor configuration file, Later in the IDE can keep some set of smooth migration. | – gitignore / / need to Git to ignore the file list | – presents – cli. Json / / presents – cli configuration file | — karma. Conf. Js / / Karma unit test configuration file | — package. Json / / the node package file | — protractor. Conf., js / / end-to-end test configuration file (integration testing) | – README. Md | — tslint. Json / / code to check the configuration of the Lint static | – e2e / / end-to-end test code directory | | – app. E2e – spec. Ts | | – app. Po. Ts | | — tsconfig. Json | | — – / SRC/source code Favicon. Ico / / site collection icon | — index. HTML / / | – the main entry page. The ts / / entrance ts file | — polyfills. Ts / / | – browser capabilities enhance polyfills reference documents Styles. The CSS / / global style file | — test. Ts / / test entry documents | — tsconfig. Json / / TypeScript configuration file | — typings. Which s / / project reference file using the TypeScript of type definition | – app / / application directory | | – app.com ponent. CSS / / the style of the leading components file | | – app.com ponent. HTML / / leading components HTML templates | | – app.com ponent. Spec. Ts / / leading component test file | | – app.com ponent. Ts / / system leading components | | – app. The module. The ts / / application root module | | – index. The ts / / application gateways | | – assets/resource/site folder . | – gitkeep | – environments | — environment. Prod. Ts / / production environment configuration file | — environment. Ts / / environment configuration Probably understand the file directory structure, we returned to the command line, Type ng serve in the application root directory to see the server running on port 4200 after the application is compiled and packaged.




C1_s1_ng_serve. PNG – 42.5 kB

Open your browser and enter http://localhost:4200 to see the program running successfully!




C1_s1_project_1st_browser. PNG – 135.7 kB

It’s too unfulfilling, isn’t it? Let’s change it. Open SRC /app/app.component.ts and modify the title, such as: title = ‘This is a hello-angular app’; Save and go back to your browser. The result has been updated. This hot loading feature makes development very convenient.




C1_s1_project_1st_browser_update. PNG – 146.5 kB

The first component

Ng generate Component login –inline-template –inline-style As the name suggests, the parameter generate is used to generate a file, the parameter Component is used to generate a component, and login is the name of our component, so you can come up with some other interesting names. The next two parameters tell angulary-CLI to generate the component by putting the component’s HTML template and CSS styles in the same file as the component. (It’s better to separate the files, but we’ll go inline for the first example.) Does it feel like the command line is too long? Luckily, the Angular team thinks the same way, so you can rewrite the command above as ng g c login-it-is, which means generate g instead of component, and C instead of Component. Similarly, the words for –inline-template are changed to it with the first letter




Image_1b27r02qlo6f11f19qg1q9k1fclm. PNG – 30.3 kB

Angular-cli generates a new folder login for us in the \ SRC \app directory, and generates two files in the login directory. Login.component.spec. ts is the test file, which we won’t talk about here. The other one is login.component.ts and that’s our new Component. Angular advocates naming the component name.component.ts, naming the component’s HTML template component.component.html, and naming the component’s style file: Component.component.css, and try to follow Google’s official recommendations in your coding.

The source code for our newly generated Login component is as follows

import { Component, OnInit } from '@angular/core'; // @component is an Angular decorator function that describes Compoent metadata. // Where selector refers to the Component's tag in an HTML template. // Template is an inline HTML template. If you use a separate file, templateUrl //styles are inline CSS styles, and if you use a separate file, styleUrls @component ({selector: 'app-login', template: '

login Works!

`, styles: [] }) export class LoginComponent implements OnInit { constructor() { } ngOnInit() { } }Copy the code

So how do we use this component once it’s built? Note that the @Component in the code above decorates the selector in the configuration: ‘app-login’, which means we can use it in the template of other components to reference our Component.

Now we open Hello-Angular\ SRC \ App \app.component.html to add our component references

{{title}}

Copy the code

When you save it and return to your browser, you can see that our first component is displayed.




image_1b27qsmhp1nlrb8g1uh6cp71qcj9.png-19kB

Some basic concepts

Here we introduce some basic Angular concepts that will be explained in more detail in later chapters.

What is a module?

Simply put, a module is a functional block that provides relatively independent functionality, each focused on a specific business domain. Many Angular libraries are provided as modules. FormsModule encapsulates form processing, HttpModule encapsulates Http processing, and so on. Every Angular app has at least one module class, the root module, which we boot to launch the app. By convention, the class name of the root module is AppModule and is placed in the app.module.ts file. The root module in our example is located in hello-angular\ SRC \app\app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }Copy the code

The @NgModule decorator is used to define metadata for modules. Declarations list the top-level components in the application, including the tutorial AppComponent and the LoginComponent we just created. Components declared in a Module can be used directly within the Module. That is, any Component in the same Module can use the declared Component directly in its template file, just as we did at the end of the AppComponent template.

Imports introduces three helper modules:

  • BrowserModule provides key services and directives for applications running in the browser. All applications running in the browser must reference BrowserModule.
  • FormsModule provides services and directives such as form processing and two-way binding
  • HttpModule provides Http request and response services

Providers lists the services that are “injected” in this module. Dependency injection is explained in more detail in a later section. Bootstrap specifies which component is the tutorial component (AppComponent in this case). When Angular bootstraps the app, it renders the tutorial component in the DOM and places the result in the element tag of the component in index.html (app-root in this case).




  
  HelloAngular
  

  
  


  Loading...


Copy the code

The boot process

Angular2 launches the app by bootstrapping the AppModule in main.ts. Angular provides many boot options for different platforms. The following code is dynamically booted by a JUST-in-time (JiT) compiler, which is generally the default for development debugging.

//main.ts import './polyfills.ts'; Import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; import { environment } from './environments/environment'; import { AppModule } from './app/'; if (environment.production) { enableProdMode(); } // The Angular compiler compiles and boots the application in the browser platformBrowserDynamic().bootstrapModule(AppModule);Copy the code

The alternative is static boot using aoT-Ahead-of-time, which produces smaller, faster applications and is preferred, especially on mobile devices or high-latency networks. With the static option, the Angular compiler runs ahead of time as part of the build process, generating a set of class factories. At their heart is the AppModuleNgFactory. The syntax for bootstrapping the precompiled AppModuleNgFactory is similar to how you bootstrapping the AppModule class dynamically.

Import {platformBrowser} from '@angular/platform-browser'; import {platformBrowser} from '@angular/platform-browser'; AppModuleNgFactory import {AppModuleNgFactory} from './app.module. ngFactory '; // BootStrap AppModuleNgFactory platformBrowser(). BootstrapModuleFactory (AppModuleNgFactory);Copy the code

This section code: github.com/wpcfan/awes…

We’ll continue that in the next video, but remember that if your uncle can learn something, so can you.

Section 1: Angular 2.0 from 0 to 1 (I) Section 2: Angular 2.0 from 0 to 1 (II) Section 3: Angular 2.0 from 0 to 1 (III) Section 4: Angular 2.0 from 0 to 1 (IV) Section 5: Angular 2.0 from 0 to 1 (IV) Angular 2.0 from 0 to 1 (5) Section 6: Angular 2.0 from 0 to 1 (6)