Table of Contents
NgDoBootstrap
在 AOT 中能工作么?
Home Web Front-end JS Tutorial How to manually start an Angular program? Detailed explanation of manually starting the angularjs program

How to manually start an Angular program? Detailed explanation of manually starting the angularjs program

Sep 07, 2018 pm 04:52 PM
angular.js typescript

This article mainly introduces how to manually start the angularjs program. Here is a detailed explanation of how to manually start the angularjs program. Now let us take a look at how to manually start the angularjs program

Angular official documentation states that in order to start the Angular program, the following code must be written in the main.ts file:

platformBrowserDynamic().bootstrapModule(AppModule);
Copy after login

This line of codeplatformBrowserDynamic() is to construct a platform. Angular’s ​​official documentation defines platform as (Translator’s Note: For clear understanding, platform Definition not translated):

the entry point for Angular on a web page. Each page has exactly one platform, and services (such as reflection) which are common to every Angular application running on the page are bound in its scope.

At the same time, Angular also has the concept of running application instance, which you can use the ApplicationRef token to inject as a parameter to obtain its examples. The platform definition above also implies that a platform can have multiple application objects, and each application object is passed bootstrapModule is constructed, and the construction method is the same as that used in the main.ts file above. Therefore, the code in the main.ts file above first constructs a platform object and an application object.

When the application object is being constructed, Angular will check the bootstrap attribute of the module AppModule, which is used to start the program :

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}
Copy after login

bootstrap The attribute usually contains the component used to start the program (Translator's Note: Root component). Angular will query and match the selector of the startup component in the DOM. Then instantiate the startup component. (If you want to see more, go to PHP Chinese website AngularJS Development Manual to learn)

Angular startup process implies which component you want to start the program, but if the component of the startup program What should I do if it is defined at runtime? When you get the component, how do you start the program? It's actually a very simple process.

NgDoBootstrap

Assume we have two components A and B. We will code to determine which component to use to start the program at runtime. First let us define These two components:

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

@Component({
  selector: 'a-comp',
  template: `<span>I am A component</span>`
})
export class AComponent {}

@Component({
  selector: 'b-comp',
  template: `<span>I am B component</span>`
})
export class BComponent {}
Copy after login

Then register these two components in AppModule:

@NgModule({
  imports: [BrowserModule],
  declarations: [AComponent, BComponent],
  entryComponents: [AComponent, BComponent]
})
export class AppModule {}
Copy after login

Note that because we have to customize the startup program, there is no The bootstrap property registers these two components in the entryComponents property, and by registering the component in the entryComponents, the Angular compiler (Translator's Note: Angular provides @angular/compiler package is used to compile the angular code we wrote, and also provides @angular/compiler-cli CLI tool) Factory classes will be created for these two components (Translator's Note: When Angular Compiler compiles each component, it will first convert the component class into the corresponding component factory class, that is, a.component.ts is compiled into a.component. ngfactory.ts). Because Angular will automatically add components registered in the bootstrap attribute to the entry component list, there is usually no need to register the root component in the entryComponents attribute. (Translator's Note: That is, components registered in the bootstrap attribute do not need to be repeatedly registered in entryComponents).

Since we don’t know whether the A or B component will be used, we cannot specify the selector in index.html, so index.html It seems that it can only be written like this (Translator's Note: We don't know whether the server returns A or B component information):

<body>
  <h1 id="status">
     Loading AppComponent content here ...
  </h1>
</body>
Copy after login

If At this time, the following error will occur when running the program:

The module AppModule was bootstrapped, but it does not declare “@NgModule.bootstrap” components nor a “ngDoBootstrap” method. Please define one of these

The error message tells us that Angular is complaining that we did not specify which component to use to start the program, but we really can't know in advance (Translator's Note: We don't know when the server will return anything). Later we have to manually add the ngDoBootstrap method to the AppModule class to start the program:

export class AppModule {
  ngDoBootstrap(app) {  }
}
Copy after login

Angular will pass ApplicationRef as a parameter ngDoBootstrap (Translator's Note: Refer to this line in the Angular source code), when you are ready to start the program, use the bootstrap method of ApplicationRef to initialize the root component.

Let us write a custom method bootstrapRootComponent to start the root component:

// app - reference to the running application (ApplicationRef)
// name - name (selector) of the component to bootstrap
function bootstrapRootComponent(app, name) {
  // define the possible bootstrap components 
  // with their selectors (html host elements)
  // (译者注:定义从服务端可能返回的启动组件数组)
  const options = {
    'a-comp': AComponent,
    'b-comp': BComponent
  };
  // obtain reference to the DOM element that shows status
  // and change the status to `Loaded` 
  //(译者注:改变 id 为 #status 的内容)
  const statusElement = document.querySelector('#status');
  statusElement.textContent = 'Loaded';
  // create DOM element for the component being bootstrapped
  // and add it to the DOM
  // (译者注:创建一个 DOM 元素)
  const componentElement = document.createElement(name);
  document.body.appendChild(componentElement);
  // bootstrap the application with the selected component
  const component = options[name];
  app.bootstrap(component); // (译者注:使用 bootstrap() 方法启动组件)
}
Copy after login

传入该方法的参数是 ApplicationRef 和启动组件的名称,同时定义变量 options 来映射所有可能的启动组件,并以组件选择器作为 key,当我们从服务器中获取所需要信息后,再根据该信息查询是哪一个组件类。

先构建一个 fetch 方法来模拟 HTTP 请求,该请求会在 2 秒后返回 B 组件选择器即 b-comp 字符串:

function fetch(url) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('b-comp');
    }, 2000);
  });
}
Copy after login

现在我们拥有 bootstrap 方法来启动组件,在 AppModule 模块的 ngDoBootstrap 方法中使用该启动方法吧:

export class AppModule {
  ngDoBootstrap(app) {
    fetch('url/to/fetch/component/name')
      .then((name)=>{ this.bootstrapRootComponent(app, name)});
  }
}
Copy after login

这里我做了个 stackblitz demo 来验证该解决方法。(译者注:译者把该作者 demo 中 angular 版本升级到最新版本 5.2.9,可以查看 angular-bootstrap-process,2 秒后会根据服务端返回信息自定义启动 application

在 AOT 中能工作么?

当然可以,你仅仅需要预编译所有组件,并使用组件的工厂类来启动程序:

import {AComponentNgFactory, BComponentNgFactory} from './components.ngfactory.ts';
@NgModule({
  imports: [BrowserModule],
  declarations: [AComponent, BComponent]
})
export class AppModule {
  ngDoBootstrap(app) {
    fetch('url/to/fetch/component/name')
      .then((name) => {this.bootstrapRootComponent(app, name);});
  }
  bootstrapRootComponent(app, name) {
    const options = {
      'a-comp': AComponentNgFactory,
      'b-comp': BComponentNgFactory
    };
    ...
Copy after login

记住我们不需要在 entryComponents 属性中注册组件,因为我们已经有了组件的工厂类了,没必要再通过 Angular Compiler 去编译组件获得组件工厂类了。(译者注:components.ngfactory.ts 是由 Angular AOT Compiler 生成的,最新 Angular 版本 在 CLI 里隐藏了该信息,在内存里临时生成 xxx.factory.ts 文件,不像之前版本可以通过指令物理生成这中间临时文件,保存在硬盘里。)

好了,本篇文章到这就结束了(想看更多就到PHP中文网AngularJS使用手册中学习),有问题的可以在下方留言提问。

The above is the detailed content of How to manually start an Angular program? Detailed explanation of manually starting the angularjs program. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Angular learning talks about standalone components (Standalone Component) Angular learning talks about standalone components (Standalone Component) Dec 19, 2022 pm 07:24 PM

This article will take you to continue learning angular and briefly understand the standalone component (Standalone Component) in Angular. I hope it will be helpful to you!

5 common JavaScript memory errors 5 common JavaScript memory errors Aug 25, 2022 am 10:27 AM

JavaScript does not provide any memory management operations. Instead, memory is managed by the JavaScript VM through a memory reclamation process called garbage collection.

How does Vue3+TypeScript+Vite use require to dynamically introduce static resources such as images? How does Vue3+TypeScript+Vite use require to dynamically introduce static resources such as images? May 16, 2023 pm 08:40 PM

Question: How to use require to dynamically introduce static resources such as images in a Vue3+TypeScript+Vite project! Description: When developing a project today (the project framework is Vue3+TypeScript+Vite), it is necessary to dynamically introduce static resources, that is, the src attribute value of the img tag is dynamically obtained. According to the past practice, it can be directly introduced by require. The following code: Write After uploading the code, a wavy line error is reported, and the error message is: the name "require" cannot be found. Need to install type definitions for node? Try npmi --save-dev@types/node. ts(2580) after running npmi--save-d

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!

Let's talk about how to customize the angular-datetime-picker format Let's talk about how to customize the angular-datetime-picker format Sep 08, 2022 pm 08:29 PM

How to customize the angular-datetime-picker format? The following article talks about how to customize the format. I hope it will be helpful to everyone!

A step-by-step guide to understanding dependency injection in Angular A step-by-step guide to understanding dependency injection in Angular Dec 02, 2022 pm 09:14 PM

This article will take you through dependency injection, introduce the problems that dependency injection solves and its native writing method, and talk about Angular's dependency injection framework. I hope it will be helpful to you!

See all articles