Angular Basics – Getting started

Angular implements the typescript syntax.

The basic Angular building block is an NgModule: it collects related code together. Angular applications are defined by a set of NgModules. An application will have at least one module to boot the application, and usually many feature modules:

  • Component Definition view
    • A view is a set of courseware screen elements that can be displayed and modified according to program logic and data
    • There is only one root component per application
  • Component usage service
    • Business processing logic that is not related to the view should be placed in the service
    • Services can be injected into components as dependencies, making code more modular, reusable, and efficient

Components and services are classes in nature and typically use decorators to mark their types

  • The component class metadata associates the component class with a template used to define the view.

    @Component({ / / metadata
      selector: 'app-base-info',
      templateUrl: './base-info.component.html',
      styleUrls: ['./base-info.component.scss']})Copy the code
    • Templates combine regular HTML with Angular directives and binding tags that allow Angular to modify HTML before rendering it
  • The metadata for the service class provides information that Angular uses to make the service available to components through dependency injection

    @Injectable({ / / metadata
      providedIn: 'root'
    })
    Copy the code

The module

An NgModule declares a compilation context for a set of components, focusing on an application domain, a workflow, or a closely related set of capabilities. A functional unit is formed by associating its components with a set of related code, such as a service.

Each Angular module has a companion module, usually named APPModule. The root module provides a boot mechanism to start the application.

An application usually contains many functional modules

Two NgModules can call each other’s functions [the called functions should be exported in advance]

NgModule

Angular applications are modular and have their own modular system called NgModules. An NgModule is a container for cohesive blocks of code that focus on an application domain, a workflow, or a set of closely related functions. It can contain components, service providers, or other code files whose scope is defined by the NgModule that contains them. It can also import functionality exported by other modules and export specific functionality for use by other NgModules.

@NgModule({
    providers: Provider[], 
    /* A set of injectable objects available in the injector of the current module. - The provider's dependencies are listed here that can be injected into any component, directive, pipe, or service under the injector. - Bootstrap NgModules use root injectors, which can provide dependencies for any component in the application. * /
    declarations: Array<Type<any> | any[] >,/* The group of components, directives, and pipes (collectively, declarables) that belong to this module. * /
    imports: Array<Type<any> | ModuleWithProviders<{}> | any[] >,/* The ngModules listed here export declarables that can be used in templates within the current module */
    exports: Array<Type<any> | any[] >,// Other modules can also be exported...
    /* The set of components, directives, and pipes declared in this NgModule can be used in the template of any component under the module that imports this module. The exported declarables are the module's public API. - Declarable objects should belong to only one NgModule. A module can list other modules in its exports, and all public declarables in those modules are also exported. - By default, declarable objects are private. If ModuleA does not export UserComponent, only components in this ModuleA can use UserComponent. - The export is transitive. ModuleA can import ModuleB and export it, making all exports in ModuleB available to modules that imported ModuleA. - There is no reason for the root module to export anything, because other modules never need to import the root module. * /
    entryComponents: [], // Public components in Module need to be exported here
    /* Define the set of components to compile in this NgModule so that they can be dynamically loaded into the view. * /
    bootstrap: [],
    /* Only the root module should set the bootstrap property. Components that need to be booted when this module boots. All components listed here are automatically added to entryComponents. * /
    schemas: [],
    /* The schema (HTML schema) for the declared elements allowed in the NgModule. Elements and attributes (whether Angular components or directives) must be declared in a schema. * /
    id: string./* The name or unique identifier of the current NgModule in getModuleFactory. If undefined, the module will not be registered with getModuleFactory. * /
    jit: true
	/* If true, the module will be ignored by the AOT compiler and will always be JIT compiled. This is to support future Ivy renderers and is not currently useful. * /
})
Copy the code

component

Every Angular component has at least one root component.

Each component defines a class that contains the application’s data, logic, and HTML templates

@Component({
  selector: 'app-base-info',
  templateUrl: './base-info.component.html',
  styleUrls: ['./base-info.component.scss']})Copy the code

The @Component() decorator indicates that the class immediately following it is a Component and provides template and component-specific metadata.

Templates, directives, and data binding

Template gray-board HTML is combined with Angular markup, which modifies HTML elements before they are displayed. The instructions in the template provide the program logic, and the binding tags connect the data in the application to the DOM. There are two types of data binding:

  • Event binding allows an application to respond to user input in the target environment by updating the application’s data
  • Property binding inserts processed data into HTML

Templates can also pipe values to be displayed to enhance the user experience.

Templates and Views

You define a component’s view through its companion template. A template is a form of HTML that tells Angular how to render the component.

Views are usually organized hierarchically, allowing you to modify, show, or hide on a UI partition or page basis. A template directly associated with a component defines the host view for that component. The component can also define a hierarchical view that contains embedded views that act as hosts for other components.

Two-way data binding

There are four forms of data binding tags:

  • {{ value }}= > DOM components
  • [property]="value"= > DOM components
  • (event)="handler"DOM = > component
  • [(ng-mudel)]="property"Component < = > DOM

The pipe

Declare the conversion logic for the display value in the template. A class with the @pipe decorator defines a conversion function that converts the input value into an output value for the view to try first. Angular built-in Pipes: Pipes API list.

Method of use: {{interpolated_value | pipe_name}}.

instruction

Angular templates are dynamic. When Angular renders them, it transforms the DOM according to instructions given by the directive. A Directive is a class with an @Directive() decorator.

A Component is technically a Directive, but because components are so unique and important to Angular applications, Angular defines the @Component() decorator, which extends the @Directive() decorator with template-oriented features.

In addition to components, there are two types of directives: structural and attribute directives. Angular defines both types of directives, and you can use the @directive () decorator to define your own directives.

Like a component, the metadata of an instruction associates the instruction class it decorates with a selector used to insert that instruction into HTML. In templates, directives usually appear as attributes on element tags, either as names only or as assignment targets or binding targets.

Structural instruction

Structural directives modify the layout by adding, removing, or replacing DOM elements.

  • *ngFor
  • *ngIf

Attribute instruction

Attribute directives modify the appearance or behavior of existing elements.

Services and dependency injection

service

A service is a broad concept that includes any values, functions, or features required by an application. A narrowly defined service is a class with a clearly defined purpose. It should do something concrete and do it well. Service classes can be created logically, regardless of a particular view, when you want to share data across components.

Ideally, the component’s job is to focus on the user experience and nothing else. It should provide properties and methods for data binding to act as an intermediary between the view (rendered by the template) and the application logic (usually containing some concept of the model).

Service classes are defined immediately after the Injectable() decorator. This decorator provides metadata that allows services to be injected into the client component as dependencies.

You must register at least one provider for any service you want to use. A service can register itself as a provider in its own metadata, making itself available anywhere. Alternatively, you can register providers for specific modules or components. To register a provider, provide its metadata in the @Injectable() decorator of the service, or in the @NgModule() or @Component() metadata.

By default, the Angular CLI ng Generate service provides metadata in the @Injectable() decorator to register it with the root injector.

@Injectable({
    providedIn: 'root'
})
Copy the code

Dependency injection

DI is integrated into the Angular framework and is used to provide services or whatever else is needed for newly created components anywhere. A component is a consumer of a service, that is, you can inject a service into the component so that the component class can access the service class.

Dependency injection [DI] keeps component classes lean and efficient. With DI, instead of fetching data from the server, validating user input, or writing logs directly to the console, components delegate these tasks to services.

routing

Angular’s Router module provides a service that allows you to define paths to use when navigating between different application states and view hierarchies. Its working model is based on well-known browser navigation conventions:

  • Type the URL in the address bar and the browser navigates to the appropriate page.
  • Click a link in the page and the browser navigates to a new page.
  • Click the browser’s forward and back buttons and the browser navigates forward and backward through your browsing history.

However, routers map urL-like paths to views rather than pages. When the user performs an action (such as clicking a link), a new page should be loaded in the browser, but the router intercepts the browser’s action and shows or hides a view hierarchy.

If the router determines that the current state of the application requires a particular function, and the module that defines that function has not been loaded, the router lazily loads that module on demand.

Components, views, services

The life cycle

Each component has a life cycle managed by Angular.

Component life cycle

Directives and component instances have a life cycle: They are triggered when Angular creates, updates, and destroys them. By implementing one or more lifecycle hook interfaces defined in the Angular Core library, we can execute specific methods at specific times.

Life cycle sequence

When Angular creates a component or directive using a constructor, it calls the lifecycle hook methods at specific times in the following order:

hook Use and Timing
ngOnChanges() Responds when Angular (re) sets the data binding input property. This method accepts the values of the current and previous attributesSimpleChangesObjects in thengOnInit()Called before and when the value of one or more of the bound input properties changes.
ngOnInit() Initialize the directive/component after Angular first displays the data binding and set directive/component input properties. In the first roundngOnChanges()Call when done, call onlyAt a time.
ngDoCheck() Detect, and react to changes that Angular can’t or won’t detect itself. During each change detection cycle, immediately followingngOnChanges()ngOnInit()Call later.
ngAfterContentInit() Not called when Angular projects external content into the component/directive view. For the first time,ngDoCheck()And then it’s called, only once.
ngAfterContentChecked() Called whenever Angular completes change detection of the projected component content.ngAfterContentInit()And every timengDoCheck()After the call
ngAfterViewInit() Called whenever Angular has initialized the component view and its child views. For the first time,ngAfterContentChecked()And then it’s called, only once.
ngAfterViewChecked() Called whenever Angular completes change detection for component views and child views.ngAfterViewInit()And every timengAfterContentChecked()Call later.
ngOnDestroy() Not called and cleaned before Angular destroys each directive/component. Here, unsubscribe observables and detach event handlers to prevent memory leaks. Called before Angular destroys the directive/component.