了解如何在20分钟内创建您的第一个Angular应用

2023-11-19

Angular is a JavaScript framework, created my Misko Hevery and maintained by Google. It’s an MVC (Model View Vontroller). You can visit the official page to learn more about it.

Angular是一个JavaScript框架,创建了我的Misko Hevery,并由Google维护。 这是一个MVC(模型视图Vontroller)。 您可以访问官方页面以了解更多信息。

Right now, the latest version of Angular is 5.2.10. There is first generation 1.x and second generation 2.x, and the two generations are totally different in their structures and methods. Don’t worry if you feel confused about the version, because in this article we will be using the second generation 2.x

目前,Angular的最新版本是5.2.10。第一代 1.x第二代2.x ,这两代在结构和方法上完全不同。 如果您对版本感到困惑,请不要担心,因为在本文中,我们将使用第二代2.x

目录 (Table of contents)

  • Adding an item (learn how to submit a form in Angular )

    添加项目(了解如何在Angular中提交表单)
  • Removing an item (learn how to add an event in Angular)

    删除项目(了解如何在Angular中添加事件)
  • Angular animation (learn how animate the components )

    角度动画(了解如何为组件设置动画)

先决条件: (Prerequisites:)

  • Node.js

    Node.js

Check if node.js is installed in your computer. Learn more about installation.

检查您的计算机中是否安装了node.js。 了解有关安装的更多信息

  • npm

    npm

npm (node package manager) is installed with Node.js

npm (节点程序包管理器)与Node.js一起安装

Check the node.js version:

检查node.js版本:

node -v

npm:

npm:

npm -v

Angular-CLI

角度CLI

You should have the latest version of Angular-CLI. Learn more about Angular CLI here, and find the instructions for installation.

您应该拥有Angular-CLI的最新版本。 在此处了解有关Angular CLI的更多信息并找到安装说明。

Install Angular-cli:

安装Angular-cli:

npm install -g @angular/cli

And finally, you should have:

最后,您应该具有:

  • Basic knowledge of JavaScript

    JavaScript的基础知识
  • HTML and CSS fundamentals

    HTML和CSS基础

You don’t need to have any knowledge of Angular.

您不需要了解Angular。

Now that we have the environment to run our Angular app, let’s get started!

现在我们有了运行Angular应用程序的环境,让我们开始吧!

创建我们的第一个应用 (Creating our first app)

We will use angular-cli to create and generate our components. It will generate services, router, components, and directives.

我们将使用angular-cli创建和生成组件。 它将生成服务,路由器,组件和指令。

To create a new Angular project with Angular-cli, just run:

要使用Angular-cli创建一个新的Angular项目,只需运行:

ng new my-app

The project will be generated automatically. Let’s create our to-do app!

该项目将自动生成。 让我们创建我们的待办应用!

ng new todo-app

Then, open the files in your text editor. I use Sublime text, but you can choose any editor.

然后,在文本编辑器中打开文件。 我使用Sublime文本,但是您可以选择任何编辑器。

Here’s what the app structure looks like:

应用程序结构如下所示:

Don’t worry if you are confused about the files. All of our work will be in the app folder. It contains five files:

如果您对文件感到困惑,请不要担心。 我们所有的工作都将在app文件夹中。 它包含五个文件:

Note: Angular 2 uses TypeScript, in which files end with “.ts”extension.

注意:Angular 2使用TypeScript ,其中文件以“ .ts”扩展名结尾。

To make a nice interface for our app, we will use the Bootstrap 4 Framework.

为了使我们的应用程序界面美观,我们将使用Bootstrap 4 Framework。

Include bootstrap cdn in index.html:

index.html中包含引导CDN

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Run the app in your terminal:

在终端中运行该应用程序:

ng serve

The app will run in http://localhost:4200/

该应用程序将在http:// localhost:4200 /中运行

All is well ?!

一切都很好 ?!

Now let’s do some HTML structuring. We will use Bootstrap classes to create a simple form.

现在让我们进行一些HTML结构化。 我们将使用Bootstrap类创建一个简单的表单。

app.component.html:

app.component.html

<div class="container"> <form>  <div class="form-group">  <h1 class="text-center text-primary">Todo App</h1>   <div class="input-group-prepend">       <input type="text" class="form-control" placeholder="Add Todo" name="todo">    <span class="input-group-text">Add</span>   </div>  </div> </form></div>

In app.component.css:

app.component.css中

body{ padding: 0; margin: 0;
}form{ max-width: 25em; margin: 1em auto;}

To capture the input value in Angular 2, we can use the ngModel directive. You can insert a variable as an attribute inside the input element.

要捕获Angular 2中的输入值,我们可以使用ngModel指令。 您可以在输入元素中插入变量作为属性。

<input type="text" #todo class="form-control" placeholder="Add Todo" name="todo" ngModel>

To create a variable as an attribute, use # followed by the variable’s name.

要将变量创建为属性,请使用后跟变量名称。

<input #myVariable type="text" name="text" ngModel>
// get the value of the Variable<p>{{myVariable.value}}</p>

Now get the “todo” variable value:

现在获取“ todo”变量值:

<p>{{todo.value}}</p>

All is well ?!

一切都很好 ?!

Now we have to store the value captured from the input. We can create an empty array in app.component.ts inside the AppComponent class:

现在我们必须存储从输入中捕获的值。 我们可以创建在AppComponent类中app.component.ts空数组:

export class AppComponent {  todoArray=[] }

Then we have to add a click event to our button that pushes the value captured into “todoArray”.

然后,我们必须在按钮上添加一个click事件,该事件会将捕获的值推送到“ todoArray ”中。

app.component.html:

app.component.html

<span class="input-group-text" (click)="addTodo(todo.value)">Add</span>

In app.component.ts:

app.component.ts中

export class AppComponent { todoArray=[]
addTodo(value){    this.todoArray.push(value)    console.log(this.todos)  } }
Use console.log(this.todoArray) to see Array value
使用console.log(this.todoArray)查看数组值

从“ todoArray”中获取数据 (Fetch data from “todoArray”)

Now we have to fetch data stored in “todosArray.” We will use the *ngFor directive to loop through the array and extract the data.

现在我们必须获取存储在“ todosArray”中的数据。 我们将使用* ngFor指令遍历数组并提取数据。

app.component.html:

app.component.html:

<div class="data">  <ul class="list-instyled">   <li *ngFor="let todo of todoArray">{{todo}}</li>  </ul>  </div>

After fetching data:

提取数据后:

The data will now be fetched automatically when we click the add button.

现在,当我们单击添加按钮时,将自动获取数据。

造型应用 (Styling the app)

I like to use Google-fonts and Material-icons, which are free to use.

我喜欢使用Google字体Material-icons ,它们是免费使用的。

Include Google fonts inside app.component.css:

app.component.css中包含Google字体:

/*Google fonts*/@import url('https://fonts.googleapis.com/css?family=Raleway');

And Material-icons inside index.html:

还有index.html中的 Material-icons:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

After adding some styling to our app, it will look like this:

在为我们的应用添加一些样式后,它将如下所示:

To use Material icons:

要使用“材质”图标:

<i class="material-icons>iconName</i>

Add “delete” and “add” icons in app.component.html:

app.component.html中添加“删除”和“添加”图标:

// put add icon inside "input-group-text" div
<span class="input-group-text" (click)="addTodo(todo.value)"><i class="material-icons">add</i></span>
// and delete icon inside list item <li *ngFor="let todo of todoArray">{{todo}}<i class="material-icons">delete</i></li>

For styles in app.component.css:

对于app.component.css中的样式:

/*Google fonts*/@import url('https://fonts.googleapis.com/css?family=Raleway');
body{ padding: 0; margin: 0;
}form{ max-width: 30em; margin: 4em auto; position: relative; background: #f4f4f4; padding: 2em 3em;}form h1{    font-family: "Raleway";    color:#F97300; }form input[type=text]::placeholder{   font-family: "Raleway";   color:#666; }form .data{    margin-top: 1em;}form .data li{ background: #fff; border-left: 4px solid #F97300; padding: 1em; margin: 1em auto; color: #666; font-family: "Raleway";}form .data li i{    float: right;    color: #888;    cursor: pointer;}form .input-group-text{    background: #F97300;    border-radius: 50%;    width: 5em;    height: 5em;    padding: 1em 23px;    color: #fff;    position: absolute;    right: 13px;    top: 68px;    cursor: pointer;}form .input-group-text i{    font-size: 2em;}form .form-control{ height: 3em;    font-family: "Raleway";}form .form-control:focus{ box-shadow: 0;}

Our app is almost done, but we need to add some features. A delete functionality should let users click a delete icon and delete an item. It would also be great to have the option to enter a new item with the return key, instead of clicking the add button.

我们的应用程序即将完成,但是我们需要添加一些功能。 删除功能应使用户单击删除图标并删除项目。 可以选择使用返回键输入新项目,而不用单击添加按钮,这也很好。

Deleting items

删除项目

To add the delete functionality, we will use the “splice” array method and a for loop. We will loop through “todoarray” and extract the item we want to delete.

为了添加删除功能,我们将使用“拼接”数组方法和一个for循环。 我们将遍历“ todoarray”并提取要删除的项目。

Add a (click) event to delete icon and give it “todo” as parameter :

添加一个(单击)事件以删除图标,并将其“ todo”作为参数:

<li *ngFor="let todo of todoArray">{{todo}} <i (click)="deleteItem(todo)" class="material-icons">delete</i></li>

In app.component.ts:

app.component.ts中

/*delete item*/  deleteItem(){   console.log("delete item")  }

When you click delete, this should show up in the console:

当您单击删除时,这应该显示在控制台中:

Now we have to loop through “todoArray” and splice the item we clicked.

现在我们必须遍历“ todoArray”并拼接我们单击的项目。

In app.component.ts:

app.component.ts中

/*delete item*/  deleteItem(todo){   for(let i=0 ;i<= this.todoArray.length ;i++){    if(todo== this.todoArray[i]){     this.todoArray.splice(i,1)    }   }  }

The result:

结果:

Awesome ?!!

太棒了!!

输入要添加的项目 (Entering to add items)

We can add a submit event to the form:

我们可以在表单中添加一个提交事件:

(ngSubmit)="TodoSubmit()"

We need to add the variable “#todoForm” to the form and give it “ngForm” as a value. In this case, we just have one field so we will just get a single value. If we have multiple fields, the submit event will return the values of all the fields in the form.

我们需要将变量“ #todoForm”添加到表单并将其“ ngForm”作为值。 在这种情况下,我们只有一个字段,所以我们只会得到一个值。 如果我们有多个字段,则Submit事件将返回表单中所有字段的值。

app.component.html

app.component.html

<form #todoForm= "ngForm" (ngSubmit)="todoSubmit(todoForm.value)"></form>

in app.component.ts

app.component.ts中

// submit Form  todoSubmit(value:any){ console.log(value)  }

Check the console. It will return an object of values:

检查控制台。 它将返回一个值对象:

So now we have to push the returned value to “todoArray”:

因此,现在我们必须将返回值推入“ todoArray”:

// submit Form  todoSubmit(value:any){     if(value!==""){    this.todoArray.push(value.todo)     //this.todoForm.reset()    }else{      alert('Field required **')    }      }

Here we are ?. The value is inserted without needing to click the add button, just by clicking “enter”:

我们来了 ?。 只需单击“输入”即可插入值,而无需单击添加按钮:

One more thing. To reset the the form after submitting, add the “resetForm()” build-in method to submit the event.

还有一件事。 要在提交后重置表单,请添加“ resetForm()”内置方法来提交事件。

<form #todoForm= "ngForm" (ngSubmit)="todoSubmit(todoForm.value); todoForm.resetForm()" ></form>

The form will reset after each submit now:

该表格将在每次提交后重置:

添加动画 (Adding animations)

I like to add a little touch of animations. To add animation, import the animations components in your app.component.ts:

我喜欢添加一些动画。 要添加动画,请在app.component.ts中导入动画组件:

import { Component,trigger,animate,style,transition,keyframes } from '@angular/core';

Then add the animations property to “@component” decorator:

然后将animations属性添加到“ @component”装饰器中:

@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css'],  animations:[   trigger("moveInLeft",[      transition("void=> *",[style({transform:"translateX(300px)"}),        animate(200,keyframes([         style({transform:"translateX(300px)"}),         style({transform:"translateX(0)"})           ]))]),
transition("*=>void",[style({transform:"translateX(0px)"}),        animate(100,keyframes([         style({transform:"translateX(0px)"}),         style({transform:"translateX(300px)"})           ]))])             ])
]})

Now the items have a nice effect when they’re entered and deleted.

现在,在输入和删除项目时它们具有很好的效果。

所有代码 (All the code)

app.component.ts

app.component.ts

import { Component,trigger,animate,style,transition,keyframes } from '@angular/core';
@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css'],  animations:[   trigger("moveInLeft",[      transition("void=> *",[style({transform:"translateX(300px)"}),        animate(200,keyframes([         style({transform:"translateX(300px)"}),         style({transform:"translateX(0)"})           ]))]),
transition("*=>void",[style({transform:"translateX(0px)"}),        animate(100,keyframes([         style({transform:"translateX(0px)"}),         style({transform:"translateX(300px)"})           ]))])             ])
]})export class AppComponent {  todoArray=[];  todo;  //todoForm: new FormGroup()
addTodo(value){    if(value!==""){     this.todoArray.push(value)    //console.log(this.todos)   }else{    alert('Field required **')  }      }
/*delete item*/  deleteItem(todo){   for(let i=0 ;i<= this.todoArray.length ;i++){    if(todo== this.todoArray[i]){     this.todoArray.splice(i,1)    }   }  }
// submit Form  todoSubmit(value:any){     if(value!==""){    this.todoArray.push(value.todo)     //this.todoForm.reset()    }else{      alert('Field required **')    }      } }

app.component.html

app.component.html

<div class="container"> <form #todoForm= "ngForm"(submit)="todoSubmit(todoForm.value); todoForm.resetForm()" >  <div class="form-group">  <h1 class="text-center ">Todo App</h1>   <div class="input-group-prepend">       <input type="text" #todo  class="form-control" placeholder="Add Todo" name="todo" ngModel>    <span class="input-group-text" (click)="addTodo(todo.value)">    <i class="material-icons">add</i></span>   </div>  </div>  <div class="data">  <ul class="list-unstyled">   <li [@moveInLeft]  *ngFor="let todo of todoArray">{{todo}} <i (click)="deleteItem(todo)" class="material-icons">delete</i></li>  </ul> </div> </form></div>

app.component.css

app.component.css

/*Google fonts*/@import url('https://fonts.googleapis.com/css?family=Raleway');
body{ padding: 0; margin: 0;
}form{ max-width: 30em; margin: 4em auto; position: relative;    background: #f4f4f4;    padding: 2em 3em;    overflow: hidden;}form h1{    font-family: "Raleway";    color:#F97300; }form input[type=text]::placeholder{   font-family: "Raleway";   color:#666; }form .data{    margin-top: 1em;}form .data li{ background: #fff; border-left: 4px solid #F97300; padding: 1em; margin: 1em auto; color: #666; font-family: "Raleway";}form .data li i{    float: right;    color: #888;    cursor: pointer;}form .input-group-text{    background: #F97300;    border-radius: 50%;    width: 5em;    height: 5em;    padding: 1em 23px;    color: #fff;    position: absolute;    right: 13px;    top: 68px;    cursor: pointer;}form .input-group-text i{    font-size: 2em;}form .form-control{ height: 3em;    font-family: "Raleway";}form .form-control:focus{ box-shadow: 0;}

We are done ?. You can find the files and code on Github.

我们完了 ?。 您可以在Github上找到文件和代码

观看演示 (See the Demo)

结论 (Conclusion)

Angular is easier than you think. Angular is one of the best JavaScript libraries, and it has great support and a nice community. It also has tools that make working with Angular fast and easy, like Angular-cli.

Angular比您想象的要容易。 Angular是最好JavaScript库之一,它具有强大的支持和良好的社区。 它还具有使Angular快速便捷地使用的工具,例如Angular-cli。

Subscribe to this mail-list to learn more about Angular.

订阅此邮件列表以了解有关Angular的更多信息。

SaidHayani@ (@hayanisaid1995) | TwitterThe latest Tweets from SaidHayani@ (@hayanisaid1995). #Web_Developer /#Frontend / #Back_end(#PHP &…twitter.com

SaidHayani @(@ hayanisaid1995)| Twitter 来自SaidHayani @(@ hayanisaid1995)的最新推文。 #Web_Developer /#Frontend / #Back_end(#PHP&... twitter.com

Here are some of the best online courses to learn Angular for free:

以下是一些免费免费学习Angular的最佳在线课程:

Angular 1.x

角1.x

Angular 2.x (recommended)

Angular 2.x (推荐)

翻译自: https://www.freecodecamp.org/news/learn-how-to-create-your-first-angular-app-in-20-min-146201d9b5a7/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

了解如何在20分钟内创建您的第一个Angular应用 的相关文章

随机推荐

  • PythonML-Day02: k-近邻、朴素贝叶斯、决策树、随机森林、交叉验证、网格搜索

    ML Day02 k 近邻 朴素贝叶斯 决策树 随机森林 交叉验证 网格搜索 1 数据分类 离散型数据 可以列举出 连续型数据 在区间内可任意划分 不可一一列举 2 机器学习算法分类 监督学习 预测 有特征值和目标值 有标准答案 分类 离散
  • BeanUtils.copyProperties的使用(浅拷贝)

    BeanUtils copyProperties的使用场景 将一个 Java 对象的属性值复制到另一个对象中 解决方法通常有2种方法 一个一个set 用BeanUtils copyProperties 很显然BeanUtils更加方便 代码
  • python中permute_PyTorch中permute的用法详解

    permute dims 将tensor的维度换位 参数 参数是一系列的整数 代表原来张量的维度 比如三维就有0 1 2这些dimension 例 import torch import numpy as np a np array 1 2
  • js-ajax

    一 ajax Asynchronous Javasript And Xml 通过Ajax向服务器请求数据 在不刷新整个页面的情况下 更新页面的内容 二 Ajax的创建 三步走 1 创建XMLHttpRequest对象 用来和服务器进行数据交
  • hdu1827Summer Holiday【tarjan强连通分量解决最小联系费用】

    1A 撒花 这比买买买开心多了 思路 既然是强连通分量的题 很容易想到形成的东西是一坨一坨的 哈哈 然后如果某一坨入度为0 那么很不幸 这一坨只能直接被威士忌通知 至于具体通知这一坨中的哪一个 枚举一遍就知道了 最后把话费求和 感觉强连通分
  • python程序运行提示Process finished with exit code -1073741819 (0xC0000005),程序终止运行...

    这个错误代码是表示程序运行时发生了访问冲突 通常是由于程序尝试访问不属于它的内存空间导致的 这可能是由于程序代码本身存在 bug 也可能是因为计算机环境问题造成的 为了解决这个问题 需要调查程序的代码 找出导致访问冲突的原因 然后修改代码以
  • 笔试题目收集(3)

    笔试题目搜集系列推荐 1 笔试题目搜集1 2 笔试题目收集2 3 笔试题目搜集3 4 笔试题目搜集4 5 笔试题目搜集5 1 下列程序输出结果 typedef union long i int k 5 char c DATE struct
  • 使用R语言进行数据对象获取的mget函数实战

    使用R语言进行数据对象获取的mget函数实战 在R语言中 我们经常需要获取由多个数据对象组成的列表 为了高效地获取这些对象 R提供了一个非常方便的函数 即mget函数 mget函数可以根据给定的对象名称 在当前环境中查找并返回相应的数据对象
  • 多类别属性预测深度架构GlideNet

    将属性 如颜色 形状 状态 动作 附加到对象类别是一个重要的计算机视觉问题 属性预测最近取得了令人振奋的进展 通常被表述为一个多标签分类问题 然而 在以下方面仍然存在重大挑战 1 预测多个对象类别上的大量属性 2 建模属性的类别依赖性 3
  • java pager,Pager 分页设计

    分页是非常基础又重复度高的功能 不论是前台 后台 或是手机版都有分页的需求 这里介绍Pager及相关代码 Pager是分页数据的封装 必要时需要与其他分页对象适配 PageObject Pageable等 详见PagerUtil publi
  • IO输入溢出(转载+整理)

    gets 防止缓冲区溢出 描述了高水平的缓冲区溢出攻击 以及讨论了为什么缓冲区溢出是如此严重的安全性问题 本专栏文章的主题是 通过防御性编程保护代码不受缓冲区溢出攻击 我们将论及 C编程语言中的主要安全性陷阱 显示应该避免特殊构造的原因 以
  • Bad owner or permissions on /root/.ssh/config

    vmware centos 部署 hadoop集群 启动hadoop节点 报错Bad owner or permissions on root ssh config 原因 SSH关于公钥认证Permission denied的问题 不能直接
  • 安装好后如何查看mysql/apache/nginx/php安装参数

    查看mysql编译参数 cat usr local mysql bin mysqlbug grep CONFIGURE LINE 查看apache编译参数 cat apachehome build config nice 查看php编译参数
  • 《机器学习》二刷超详细笔记

    博主在4月学完西瓜书时 一头雾水 觉得还是一知半解 9月开学后上完了必修的 machine learning 课程 并且自己编程实现了多种机器学习算法和论文复现后 才对机器学习有一点了解 现在再次翻阅西瓜书 很多知识点看到都豁然开朗 所以出
  • Debian 某些程序无法使用中文输入法设置方法

    debian系统下发现某些程序不能写入中文 下面是我解决的方法 sudo apt get install fcitx frontend qt5 1 我们可以通过在命令行下输入 dpkg L fcitx frontend qt5 1 修改配置
  • 如何解决apt-get中Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify的问题

    在Ubuntu中用apt get安装软件 系统报出Unmet dependencies错误 Unmet dependencies Try apt fix broken install with no packages or specify
  • 【Python-Anaconda】在anaconda中创建、激活虚拟环境;在anaconda中所创建的虚拟环境中安装OpenCv;如何在jupter notebook中使用所创建的虚拟环境

    一 在anaconda中创建虚拟环境 1 为什么要创建虚拟环境 答 为了避免库依赖冲突 所以在安装pytorch tensflow等时最好创建虚拟环境进行安装 2 创建虚拟环境步骤 1 打开anaconda prompt 输入如下代码 co
  • 基于AJAX技术提高搜索引擎排名

    描述 嵌入在你的web页面中的导航元素能够降低你的搜索引擎评价排名并且降低你的网站的响应性能 本文作者想同你一起探讨如何使用AJAX技术来解决这两个问题 许多设计良好的web站点都包含大量的与实际内容相联系的可导航信息 用于导航的HTML标
  • 【C++】抽象类

    2023年8月25日 周五上午 目录 声明抽象类 抽象类的特点 举例说明 声明抽象类 要在C 中声明一个抽象类 要求类中至少有一个纯虚函数 在C 中 一个类如果包含至少一个纯虚函数 那么这个类就被称为抽象类 总结起来 抽象类是一个包含至少一
  • 了解如何在20分钟内创建您的第一个Angular应用

    Angular is a JavaScript framework created my Misko Hevery and maintained by Google It s an MVC Model View Vontroller You