Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to apply Angular single page

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to apply Angular single page". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Angular layout template

Bootstrap is a general-purpose css library, and angular has released its own css library-angular material design.

Angular material design's official website is https://material.angular.io.

The official website of domestic ant design of anular is https://ng.ant.design.

Angular: component-oriented Design pattern

Why use Angular?

Built by the Google team, the upgrade is relatively fast and the community is active.

Unidirectional binding

Two-way binding

Single page application

Routin

Network request, a major focus of the front-end framework is the network request.

Component-based

Component-oriented design pattern:

View html: view html view template.

Class:code code, typescript, data&methods data and methods.

Metadata:information decorator information decorator (instruction)

Hands-on experiment-- creating Angular6 Project

First of all, confirm the Angular official website https://angular.io/.

Then install node.js and download it from the official website https://nodejs.org/en/download/.

Npm install-g @ angular/cli

Hey, it's stuck here, and the progress bar doesn't move.

Last night, it took more than an hour to get the angular operating environment.

To create a project, first create a project directory, and then enter this directory.

Cd D:\ npm-library\ angular-project

Enter the instructions to create the project:

Ng new my-app

Then a few questions will pop up for you to choose. There is no choice in the teacher's interface. It is estimated that there is a difference in the version.

The following question is whether you need more stringent type checking and bundling import, which can help you find errors in advance. For more information, please check it on the website. I chose y.

Do you want to enforce stricter type checking and stricter bundle budgets in the workspace? This setting helps improve maintainability and catch bugs ahead of time. For more information, see https://angular.io/strict (yPao)

The following question is to ask you whether to add Angular routing, I chose y.

Would you like to add Angular routing? (YBO)

The following option allows you to select a template. I chose CSS.

? Which stylesheet format would you like to use? (Use arrow keys) > CSS SCSS [https://sass-lang.com/documentation/syntax#scss] Sass [https://sass-lang.com/documentation/syntax#the-indented-syntax] Less [http://lesscss.org] Stylus [https://stylus-lang.com]

Wait patiently for the project to be created. I found a hint of "Packages installed successfully." It means that the project has been created, but there is also a prompt below, "'git' is not an internal or external command, nor is it a runnable program."

Or batch files. "according to the prompts, I speculate that git is needed to create the project, but I don't have git installed on my system, so now I need to install git.

According to the method taught by the teacher, go to bing.com to search for "official site" (search the official website in the Bing international version, there are no ads, and make sure you find the real official website. Here I complain about a certain degree, there are too many advertisements, and what I often find is not the official website.

Go to git's official website to download the git tool at https://git-scm.com/downloads. Mine is a win10 system, downloaded is 64-bit git for windows setup, and the file size is 46.3MB.

After installing git, don't forget to add the environment variable for git. I added an item to the path variable:

C:\ Program Files\ Git\ bin

Close powershell and re-run a powershell as an administrator for the environment variable you just added to take effect. Enter the command "git" to test whether a git can be called properly.

After the test is correct, delete the my-app and then rebuild the project. Pay attention to whether there is any error message.

Run the project

Before running the project, the teacher spent a lot of time talking about the pros and cons of complex engineering created by instructions and visual interface creation project and vue creation project. It means that complex projects created by instructions are more efficient when actually doing a project, so you might as well try to create a project while learning.

After the project has been created, enter the project directory just now:

Cd.\ my-app\

Run the project:

Ng serve-open

At run time, there is a question for you to choose from:

? Would you like to share anonymous usage data about this project with the Angular Team atGoogle under Google's Privacy Policy at https://policies.google.com/privacy? For moredetails and how to change this setting, see http://angular.io/analytics. (Ybig N)

It means to ask if you would like to share some data about the project anonymously to the Angular team. For more information, please go to the website. I recommend N.

After enter, the system will compile the project, and the completion of the compilation will prompt:

Compiled successfully.

The teacher talked a lot about the advantages of compilation in class. In the process of compilation, the system will analyze and check the code and find that errors will report errors. The process of compilation is the process of debugging, that is, the original typescript code is compiled into JavaScript code. This is a great improvement to the efficiency of development.

After that, the web content of the project is automatically opened, which is as follows:

Note: this picture is different from the teacher's picture, or because of the different Angular version.

Next, close the powershell window and web page, and use vscode to open the project directory.

Next, open the src directory and take a closer look at the files in it. Main.ts is the project entry. The contents of the files are as follows:

Import {enableProdMode} from'@ angular/core';import {platformBrowserDynamic} from'@ angular/platform-browser-dynamic';import {AppModule} from'. / app/app.module';import {environment} from'. / environments/environment';if (environment.production) {enableProdMode ();} platformBrowserDynamic () .bootstrapModule (AppModule) .catch (err = > console.error (err))

Where .bootstrapModule means startup module, and its argument is AppModule.

Web applications are composed of modules (module); modules are composed of components (component)

The component consists of three parts: Template, Class and Metadata.

Template:View, HTML, that is, the web page, the content displayed.

Class:Code, TypeScript, Data & Methods, that is, code, data, method.

Metadata:Information Decorator, that is, special content defined by Angular, such as decorators, etc.

Check the app directory to find the corresponding file: app.module.ts (module), and view the contents of the app.module.ts file:

Import {BrowserModule} from'@ angular/platform-browser';import {NgModule} from'@ angular/core';import {AppRoutingModule} from'. / app-routing.module';import {AppComponent} from'. / app.component';@NgModule ({declarations: [AppComponent], imports: [BrowserModule, AppRoutingModule], providers: [], bootstrap: [AppComponent]}) export class AppModule {}

View the contents of the app.component.ts (component) file:

Import {Component} from'@ angular/core';@Component ({selector: 'app-root', templateUrl:'. / app.component.html', styleUrls: ['. / app.component.css']}) export class AppComponent {title = 'my-app';}

Notice that templateUrl:'. / app.component.html' points to a web page file.

Check the app.component.html file. Comparing the contents of this file with those displayed by http://localhost:4200/, you can find that all the contents displayed by myapp are defined in this file.

Change the title in the app.component.ts file to "my first Angular application", and then check that the web page content has been updated as shown below:

You can see that title has become our modified content, "my first Angular application," but followed by "app is running!" What's going on?

Copy "app is running!" and look for it in the app.component.html file. You can see {{title}} app is runningboxes, where the output of the title is controlled. Modify it to welcome {{title}}, and then check that the content of the page has been updated as shown below:

Through the above modification test, we can learn that the web application modification can take effect immediately. Because the back-end service is running all the time, the modified code and web page content will be refreshed and effective immediately.

Now app development popular code (.ts file), structure (.html file), style (.css) separation.

You can see that there is an app.component.css under the project directory, and the style is written here.

Try to modify the file as follows:

Span {color:red;}

You can see that the font of the web page immediately turns red:

The above case also illustrates an one-way data binding concept. It is convenient to maintain complex pages.

Open app.component.html, find {{, delete a {, and then look at the page content will be white, not displayed.

Press ctrl+shift+i, open the console tab, you can see the error content, according to the error content can be checked bug.

The problem solved by the framework is to allow simple, repetitive work to be done on a computer, allowing programmers to focus on solving business logic.

The above is the basic framework of the angular project, and then try to create new components.

Create a component

The first step in creating a component is to pay attention to the path, and be sure to create a component under the current project path. Create component commands:

Ng g c productlist

The above is abbreviated, and the full command is ng generate component productlist to create a list of items.

The creation result is as follows:

CREATE src/app/productlist/productlist.component.html (26 bytes) CREATE src/app/productlist/productlist.component.spec.ts (661bytes) CREATE src/app/productlist/productlist.component.ts (295bytes) CREATE src/app/productlist/productlist.component.css (0 bytes) UPDATE src/app/app.module.ts (495bytes)

Next, continue to create "productcreate", "orderlist" and "ordercreate"

Ng g c productcreateng g c orderlistng g c ordercreate

The above four components have been created. After the components are created here, corresponding changes will occur in the project. Next, open the project directory my-app with vscode, and you can see that there are four more subdirectories under the project directory, named productlist, productcreate, orderlist and ordercreate. There are four files under the subdirectory, and the suffixes are .css, .html, .spec.ts, .ts files.

Recompile, open the project and find that the page has not changed because the component has not yet joined the page.

Introduce the concept of routing, the front-end concept of two key points-routing, network request.

View app.module.ts and add routes:

Import {RouterModule, Routes} from'@ angular/router'

Const routes: Routes = [{path: 'productlist', component: ProductlistComponent}, {path:' productcreate', component: ProductcreateComponent}, {path: 'ordetlist', component: OrderlistComponent}, {path:' ordercreate', component: OrdercreateComponent},]

Notice @ NgModule ({the declarations tag below already has five records, and declarations means to declare. The following import needs to add a component import to take effect.

Imports: [BrowserModule, AppRoutingModule, RouterModule.forRoot (routes)]

Next, look at the page and find that there is still no change, because the contents of the html files for the four newly created components have not been written to anything. Next, modify the app.component.html file to add the navigation bar for the new component.

Merchandise list create order list create order

Then look at the page and find that there is already a navigation bar, after clicking, notice that the address of the above page will change, but the page has not changed.

Next, sort out the loading order of the web page:

The first is indexhtml, which is internal only, and then you can find the following in the app.component.ts file:

@ Component ({selector: 'app-root', templateUrl:'. / app.component.html', styleUrls: ['. / app.component.css']})

Here you can see that the page displayed by root points to app.component.html and the corresponding .css file.

Take a look at the app.module.ts file:

Imports: [BrowserModule, AppRoutingModule, RouterModule.forRoot (routes)]

Routes maps to the corresponding web page according to the following table:

Const routes: Routes = [{path: 'productlist', component: ProductlistComponent}, {path:' productcreate', component: ProductcreateComponent}, {path: 'ordetlist', component: OrderlistComponent}, {path:' ordercreate', component: OrdercreateComponent},]

Then look at the contents of the html file in one of the components, "productlist".

Productlist works!

After the above combing, understand the route jump process, and then try to refresh the page, click the navigation bar to see the change.

Now try to decorate the page, introduce bootstrap through the terminal instruction, enter the project path, and enter the project instruction:

Npm install bootstrap-save

Here again encountered a pit, many errors and installation failures, probably because of the wall, the solution is to use cnpm instructions, which means to use Taobao software warehouse, not the official software repository.

It is recommended that you install bootstrap in the following order:

Cnpm i jquery-savecnpm I popper.js-savecnpm install bootstrap-save

Pay attention to the installation process, pay attention to the error message, when you see the following screen shows that the bootstrap installation is correct.

After the installation is complete, go back to the current project and take a look at the entire project directory, in which there is a styles.css file, which is in the same level as the app directory, which means the global style defined by the file, that is, the style of the whole app.

Edit styles.css and import the bootstrap package.

@ import "~ bootstrap/dist/css/bootstrap.min.css"

Edit the app.component.html file to change the style of the navigation bar. First of all, find the Documentation (document) from the bootstrap official website, click Components (component) in the sidebar, select an appropriate style, click the copy (copy) button on the right side of the style, paste (paste) it into the file, comment its contents, and copy the template.

Nav class= "nav", where nav is a nav introduced from bootstrap, and the same is true of class= "nav-link" below.

Now that the navigation bar has been beautified, recall the card we did last time, and we can copy it over and put it in the productlist. Then click on the list of items and three card will pop up. Note that the number of card automatically adjusts when you zoom the page, which is now the popular responsive layout that automatically adapts to the user's screen.

Build data:

Data is divided into static data and dynamic data, static data refers to fixed data, dynamic data refers to data obtained dynamically from files or servers.

Final page effect:

First, new a file under the app directory with the file name product.ts, edit its contents, and define the product class:

Export class product {title!: String; detail!: String; image_url!: String; price!: Number;}

Secondly, create the analog data file mock-product.ts, edit its contents, and write the data:

Import {product} from ". / product" Export const PROUDUCTS: product [] = [{title: "Projector", detail: "JmGo J7", image_url: "https://img11.360buyimg.com/n7/jfs/t1/125904/1/19039/83867/5fb4e6eaE23e725b2/59aaf9823d75043e.jpg", price: 2999}, {title:" Projector ", detail:" JmGo J7 " Image_url: "https://img11.360buyimg.com/n7/jfs/t1/125904/1/19039/83867/5fb4e6eaE23e725b2/59aaf9823d75043e.jpg", price: 2999}, {title:" Projector ", detail:" JmGo J7 ", image_url:" https://img11.360buyimg.com/n7/jfs/t1/125904/1/19039/83867/5fb4e6eaE23e725b2/59aaf9823d75043e.jpg", price: 2999},]

Edit the productlist.component.html file and modify it as follows:

{product.image_url}} "alt=" card-img-cap "> {{product.title}} {{product.detail}}

{{product.price}}

add to cart

Note that * ngFor= "let product of products" means to loop elements from the products array, where {{product.title}} is a variable, and it is worth fetching from the array elements.

Next, you can try to beautify the details, such as adding the shopping cart button to red, that is, changing its code to btn-danger, and then refreshing the page to see that the shopping cart button color has turned red. Then try to change the label color of the price and the label color of the text and details before and after the addition.

card-img-cap

{{product.title}} {{product.detail}}

Price: {{product.price}} yuan

add to cart

Then try to add data to the mock-products.ts file and repeat three records. Now there are six pieces of data in the products array. Refresh the web page again to see if there are six card. You can confirm that there are 6 card in the page. This is dynamic data.

This is the end of the content of "how to use a single page of Angular". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report