Web Front-end
JS Tutorial
How to manually start an Angular program? Detailed explanation of manually starting the angularjs programHow to manually start an Angular program? Detailed explanation of manually starting the angularjs program
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);
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 {}
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 {}
Then register these two components in AppModule:
@NgModule({
imports: [BrowserModule],
declarations: [AComponent, BComponent],
entryComponents: [AComponent, BComponent]
})
export class AppModule {}
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):
<h1> Loading AppComponent content here ... </h1>
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) { }
}
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() 方法启动组件)
}
传入该方法的参数是 ApplicationRef 和启动组件的名称,同时定义变量 options 来映射所有可能的启动组件,并以组件选择器作为 key,当我们从服务器中获取所需要信息后,再根据该信息查询是哪一个组件类。
先构建一个 fetch 方法来模拟 HTTP 请求,该请求会在 2 秒后返回 B 组件选择器即 b-comp 字符串:
function fetch(url) {
return new Promise((resolve) => {
setTimeout(() => {
resolve('b-comp');
}, 2000);
});
}
现在我们拥有 bootstrap 方法来启动组件,在 AppModule 模块的 ngDoBootstrap 方法中使用该启动方法吧:
export class AppModule {
ngDoBootstrap(app) {
fetch('url/to/fetch/component/name')
.then((name)=>{ this.bootstrapRootComponent(app, name)});
}
}
这里我做了个 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
};
...
记住我们不需要在 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!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft






