Angular 2 study notes

Angular 2 applications mainly consist of the following parts:

1. Modules:
2. Components:
3. Templates​​​​​​:
4. Metadata (Metadata):
5. Data Binding
6. Directives
7. Service ( Services):
8. Dependency Injection
9. Route: Establish URL paths and components According to the corresponding relationship between them, the corresponding components are matched and rendered according to different URL paths.

1. Metadata

Metadata is when defining modules, components, and services.DecoratorThe parameter content in the method , for example, the metadata of an AppComponent is the parameters in @Component, as follows:

{
   selector : 'mylist',
   template : '<h2>元数据</h2>'
   directives : [ComponentDetails]
}

In Angular2, Decorators are used extensively. When we define templates, components, services, and instructions, we use Decorators to define them. As the name suggests, Decorator is to add some Extraproperties or methods.

For example, the root component AppComponent can be defined as an Angular component through @Component when defining it. Then we set the selector, template and style corresponding to this component in this metadata.

In this way, when the Angular framework parses this class, it will parse and initialize it according to the rules of the component.

When the label set by this selector is encountered in a page, the component will be initialized, the template will be rendered, HTML will be displayed in the corresponding label, and the style will be applied.

2. Modules

Module refers to a class decorated with @NgModule.

@NgModule uses a metadata object to tell Angular how to compile and run the code.

Components, services, instructions, methods, pipes, etc. can be encapsulated into a module, and their access rights can be declared as public so that components of external modules can access and use them.

Built-in module

Angular2 distributes many common functions into modules:

  • ApplicationModule: Encapsulates some startup-related tools
  • CommonModule: encapsulates some commonly used built-in instructions and built-in pipes, etc.
  • BrowserModule: Some tool libraries that are encapsulated in the runtime of the browser platform. CommonModule and ApplicationModule are packaged and exported at the same time. Therefore, BrowserModule is usually introduced when using it.
  • FormsModule and ReactiveFormsModule: encapsulate form-related component instructions, etc.
  • RouterModule: encapsulates routing-related component instructions, etc.
  • HttpModule: Encapsulates services related to network requests, etc.

Before use, you need to import the relevant module packages:

  • @angular/core: stores core code, such as change monitoring mechanism, dependency injection mechanism, rendering, etc. The implementation of core functions and decorators (@Component, @Directive, etc.) will also be stored in this module.
  • @angular/common: stores some commonly used built-in instructions and built-in pipes.
  • @angular/forms: Stores form-related built-in components and built-in instructions.
  • @angular/http: Stores services related to network requests, etc.
  • @angular/router: stores routing-related components and instructions.
  • @angular/platform-<x>: stores boot-related tools. Angular supports running on multiple platforms. Different platforms have corresponding startup tools. These startup tools will be encapsulated into different modules. For example, the browser startup tools are stored under @angular/platform-browser, and server-side rendering The startup tool is stored under @angular/platform-server.

Angular module is a class with @NgModule decorator which receives used to describe module attributes. metadata objectA

Metadata attributes of @NgModule:

  • declarations: List of Components/Directives/Pipes inside the module, declare thisInternal members of the module
  • providers: Specify the services that need to be used at the root level of the application. (There is no module-level service in Angular2, and all Providers declared in NgModule are registered in the root-level Dependency Injector)
  • imports:Import other modules, Components, Directives, Pipes, etc. exposed by other modules Can be used in components of this module. For example, after importing CommonModule, you can use NgIf, NgFor and other instructions.
  • exports: Used to controlwhich internal members are exposed to external use. Importing a module does not mean that the public members exposed by the imported module within the module will be automatically imported. Unless the imported module writes its internally imported module into exports.
  • bootstrap: usually the root component launched by the app, Generally there is only one component. Components in bootstrap will automatically be placed into entryComponents.
  • entryCompoenents: Components that will not be referenced in the template. This attribute is generally only used by ng itself, usually the bootstrap component or the routing component. ng will automatically put the bootstrap and routing components into it. This attribute will not be used unless the component is dynamically added to the dom without routing.

A simplest root module:

//app/app.module.ts 文件:


import { NgModule } from '@angular/core'; //从 @angular/core 中引入 NgModule 修饰器
import { BrowserModule } from '@angular/platform-browser';


@NgModule({
  imports:      [ BrowserModule ],
  providers:    [ Logger ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }//定义根模块

3. Components

Components are the building blocks of Angular 2 applications.

consists of three parts: TypeScript class with  decorator, HTML template and style file. @Component()

Metadata properties of @Component:

  • selector : css selector, instantiate this component on the corresponding selector in HTML.
  • styleUrls : Declare the component's style in a separate file.
  • styles : Declare styles inside the component. styles: ['h1 { font-weight: normal; }']
  • standalone: Describes whether the component requires .NgModule
  • template : A piece of HTML that tells the application how to render the component.
  • templateUrl : HTML file relative path or absolute URL. (Cannot be used with template at the same time)

A simple component:

import { Component } from '@angular/core';//从 @angular/core 中引入 NgModule 修饰器

@Component({
  selector: 'hello-world',
  template: `
    <h2>Hello World</h2>
    <p>This is my first component!</p>
  `
})
export class HelloWorldComponent {
  //在此类中的代码驱动组件的行为。
}

Use this component in html:

<hello-world></hello-world>

In an Angular2 application, a component is an attribute structure, just like the DOM tree of html. Each Angular2 application has a root component, and then it will have sub-components one by one. What you get is a component tree. Each component (except the root component) has a parent component. The value of "selector" in each component definition corresponds to an html tag in the parent component.

Component communication

In Angular, there are multiple ways to achieve parent-child component communication.

Here are a few commonly used methods:

  •  Input Properties
  •  Output Properties
  •  Services
  •  ViewChild and ContentChild

1. Input Properties

Input properties are a method used to pass data from a parent component to a child component. By using the @Input() decorator, we can define a public property in the child component to receive data from the parent component.

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

@Component({
  selector: 'app-child',
  template: '<p>{
    
    { message }}</p>'
})
export class ChildComponent {
  @Input() message: string;
}

In the above code, we use the @Input() decorator to define an input attribute named message. In the child component's template, we useinterpolation expression{ { message }} to display the received message.

2. Output Properties

The output attribute allows the child component to pass information to the parent component. By using Event trigger and the @Output() decorator, we can define an event in the child component and pass the data as the event when appropriate Parameters are sent to the parent component.

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

@Component({
  selector: 'app-child',
  template: '<button (click)="sendMessage()">Send Message</button>'
})
export class ChildComponent {
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Hello from child component');
  }
}

In the above code, we define an output property named messageEvent and use EventEmitter to create a new event. In the child component, when the user clicks the button, we trigger the messageEvent event by calling the sendMessage() method and using the emit() method, passing a string as the parameter to the parent component.

3. Services

Services are an efficient way to share data and state. By creating a shared service, we can pass data and share state between any components. Components can dependency injectservices and communicate using the methods and properties provided by the services.

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
  private message: string;

  setMessage(message: string) {
    this.message = message;
  }

  getMessage() {
    return this.message;
  }
}

In the above code, we created a service named DataService and defined a private message attribute and corresponding setting and getting methods in it. We can share data between components by injecting a DataService in the component that needs to access that data.

4. ViewChild and ContentChild

By using the ViewChild and ContentChild decorators, we can get a reference to the child component in the parent component and directly call the child component's methods or access its properties. This approach is suitable for situations where you need to interact directly with child components.

import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: `
    <app-child></app-child>
    <button (click)="callChildMethod()">Call Child Method</button>
  `
})
export class ParentComponent {
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  callChildMethod() {
    this.childComponent.childMethod();
  }
}

In the above code, we use the @ViewChild() decorator to get a reference to the ChildComponent and assign it to the childComponent property. Then, in the parent component's template, we use a button to trigger the callChildMethod() method, which calls the childMethod() method in the child component.

4. Data binding

Angular2's data update detection has a detector on each component. In this way, no matter how many bound variables there are in the application, when a data is modified, only the detector of the corresponding component will be triggered to check the data modification of it and all its sub-components.

Angular adds some syntax elements to extend HTML, allowing you to insert dynamic values ​​from components. Angular automatically updates the rendered DOM when a component's state changes.

There are four forms of data binding syntax:

1, interpolation { {}} : Display component value in HTML tag. (One way)

<h3>
{
   
   {title}}
<img src="{
   
   {ImageUrl}}">
</h3>

2. Attribute binding []: Set the attribute of the element to the value of the attribute in the component. (One way)

<img [src]="userImageUrl">

3. Event binding(): Declare an event listener (one-way) by specifying the event name in parentheses< /span>

//在组件方法名被点击时触发
<button (click)="sayMessage()">保存</button>


//组件类中定义的方法:
sayMessage() {
  alert(this.message);
}

4. Two-way binding [] (): Using the NgModel directive in Angular can make two-way binding more convenient.

<input [value]="currentUser.firstName"
       (input)="currentUser.firstName=$event.target.value" >

Two-way binding means that when the user modifies the value on the page, the value will be directly fed back to the component. Similarly, if the value is modified in some way in the component, the latest value will also be displayed on the page.

For the above​[]​ and ​()​​​   Two types of binding can be understood as 'input' and 'output'. ​​

5. Services

Angular2 does not impose any rule restrictions on the definition of services. Any class can be defined as a service. In this class, you can Contains business methods and can also contain environment configuration variables.

A simple service:

export class loggerServices {
  log(msg: any)   { console.log(msg); }
  error(msg: any) { console.error(msg); }
  warn(msg: any)  { console.warn(msg); }
}

We only need to define a class and export it.

6. Dependency Injection

Angular borrows the concept of certain container libraries in languages ​​​​such as Java, and the creation of all service instances is completed by the container. When a service needs to reference another service, it does not need to create a service instance first and then call its methods or properties through the instance. Instead, it directly obtains the instances of the corresponding service from the container without us having to worry about how to instantiate them.

In Angular2, dependency injection (Dependency Injection) is mainly used tomanage the injection of service instances.

Use the  decorator to declare that this class can be injected. @Injectable 

@Injectable​​ 
export class HeroService {
...
}

You can then inject and use it elsewhere.

1: Provide dependencies

  • At the component level, using the  decorator's providers field. In this case, HeroService will be available to all instances of this component, as well as other components and directives used in its templates. In other words, the instances of the HeroService class are shared on the current node and the components of all its child nodes.They all share a service instance . For example:@Component

@Component({
  selector: '...',
  template: '...',
  providers: [HeroService]
})
class HeroListComponent {}
  • At theNgModule level, use the  decorator  providersfield. In this case, HeroService is available to all components, directives and pipes declared in this NgModule or other modules in the same ModuleInjector as this module. When you register a provider with a specific NgModule, the same service instance is available to all components, directives, and pipes in that NgModule. To understand all edge cases, see Multistage Injectors. For example:@NgModule

@NgModule({
  declarations: [...]
  providers: [HeroService]
})
class HeroListModule {}
  • At the applicationroot level, it is allowed to be injected into other classes of the application. This can be achieved by adding the  providedIn: 'root' field to the  decorator: < /span>@Injectable

@Injectable({
  providedIn: 'root'
})
class HeroService {}

When you provide a service at the root level, Angular creates a shared instance of HeroService and injects it into any class that needs it. Registering providers in the  metadata also allows Angular to optimize the application by removing unused services from the compiled application, a process called tree-shaking. . @Injectable

2: Inject dependencies

The most common way is to declare it in the class's constructor. When Angular creates a new instance of a component, directive, or pipeline class, it determines what services or other dependencies the class requires by looking at the constructor's parameter types. For example, if HeroListComponent were to use HeroService, the constructor could look like this:

@Component({ … })
class HeroListComponent {
  constructor(private service: HeroService) {}
}

Guess you like

Origin blog.csdn.net/qianqianyixiao1/article/details/134988066