search
HomeWeb Front-endJS TutorialHow Angular CLI implements an Angular project

This time I will show you how Angular CLI implements an Angular project, and what are the precautions for how Angular CLI implements an Angular project. The following is a practical case, let's take a look.

Angular CLI is a command line interface tool that can create projects, add files, and perform a lot of development tasks, such as testing, packaging, and publishing. The quick start here is based on this command.

Before starting the project, you need to install node and npm first, and then execute npm install -g @angular/cli to install Angular CLI.

1: Use the command line to create a new project

ng new newApp --skip-install
cd newApp
cnpm install
ng serve --open

Executing the above command will automatically create a new Angualr project and start the project.

Among them, --skip-install means that the node package will not be installed first. It will be much faster if we then use cnpm install to install it.

2: Directory structure

Now let’s take a look at what the ng command helps us generate, which is the directory structure of the project, which is First, have a general understanding of what it does. You don’t have to know everything, but first remember the following ones that I feel are important:

1.src: where the application code is stored;

2 .src/app: The main place where your code is stored. This may not be appropriate, but when you develop, you spend most of your time modifying the code here;

3.src/assets: pictures, etc. Where it is stored, it will be copied to the release package when building;

4.src/main.js: You will basically not modify it, it is the main entry of the program;

5.src /styles.css: Specially used styles are written in the corresponding places. As will be mentioned later, public styles will be written here;

6.karma.conf.js: Unit test configuration for Karma. It is used when running ng test.

3: Custom component

import { Component } from '@angular/core';
@Component({
  selector: 'my-comp',
  template: '
  • ID:{{row.id}} INFO:{{row.info}}
',     styles: [`ul{background-color: antiquewhite;padding-left: 10px;list-style: none;}`]    }) export class MyComponent {   dataList = [     { id: 1, info: "Angular" },     { id: 2, info: "React" },     { id: 3, info: "Vue" }   ];   }

A very simple component has been defined above, but before using it, you still need Defined in the module, this time it is registered in src/app/app.module.ts:

import { NgModule } from '@angular/core';
import { MyComponent } from './my.component';
@NgModule({
  declarations: [
    MyComponent
  ]  
})
......

Now that it is registered, you can use it. The method of using the above example is very simple, just do it yourself A label my-comp is defined, which is used exactly the same as ordinary p.

It should be noted that for the convenience of viewing, I have removed irrelevant code in the registration example. Fortunately, the actual situation includes registration of startup, other components, services, etc. You can look at the command line For other instructions automatically generated, here we mainly explain more important things, the same below.

Similar to AngularJS, Angular's selector has other features besides the custom tags above:

1.selector: 'element-name'//Custom tag selector;

2.selector: '.class'//Style selector;

3.selector: '[attribute]'//Attribute selector;

4.selector: '[ attribute=value]'//Attribute value selector;

5.selector: ':not(sub_selector)'//Invert selector;

6.selector: 'selector1, selector2 '//Multiple selectors.

Four: Custom service

Like components, let’s define a service first.

import { Injectable } from '@angular/core';
export class DataFormat { 
  id: number; 
  info: string; 
}
@Injectable()
export class MyServ {
  getData(): DataFormat[] {
    return [
      { id: 1, info: "Angular" }, 
      { id: 2, info: "React" }, 
      { id: 3, info: "Vue" }
    ];
  }  
}

Next, let’s register it. The registration of services and components is a bit different. Let’s register it on the main component first. The default is to register it in the arc/app/app.component.ts file:

The use of the
import { Component } from '@angular/core';
import { MyServ } from './my.service';
@Component({
  providers: [MyServ]  
})

service is also very simple. Let’s use the constructor to demonstrate it here:

import { MyServ } from './my.service';
......
export class MyComponent {
  dataList: any[];  
  constructor(private demoService: MyServ) {
     this.dataList = this.demoService.getData();
    }  
}

Do you remember the code of the custom component? We demonstrated the usage of the service in it, and only the modified part of the code is given above.

5: The use of routing

We give a simple usage of routing here. The specific details are similar to the above and will be discussed separately. To discuss, the purpose of this article is to get started quickly.

For the convenience of demonstration, we have defined two components by default: MyComponent and My2Component.

First of all, you need to make sure that is defined in the head tag of the index.html page or the script that dynamically generates this element.

We first register the route in src/app/app.module.ts:

......
import { RouterModule } from '@angular/router';
@NgModule({
  declarations: [MyComponent,My2Component],  
  imports: [  
    RouterModule.forRoot([    
      {path: 'my',component: MyComponent},      
      {path: 'my2',component: My2Component}      
    ])
  ]
  ......
})
......

It is very simple to use:

<a>toMycomp</a>
<a>toMy2comp</a>
<router-outlet></router-outlet>

点击toMycomp或者toMy2comp就会跳转对应的路由设置的组件了。

六:HTTP

由于@angular/http库中的HttpModule保存着http相关的服务,需要先引入进来(这里是在src/app/app.module.ts中引入):

import { HttpModule }  from '@angular/http';
@NgModule({
  imports: [HttpModule]  
})
......

现在,http就是一个服务,下面简单演示一种用法:

......
import { Http } from '@angular/http';
......
  constructor(private http: Http) {  
    http.get('assets/XXX.json').forEach(function (data) {    
      console.log(data['_body']);      
    });    
  }  
......

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

移动端怎样做出上拉下滑刷新加载

Vue做出弹窗功能(附代码)

The above is the detailed content of How Angular CLI implements an Angular project. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different 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 WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript'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)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I 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)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This 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 LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript 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.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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