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 JavaScriptJavaScript的基础知识
  • HTML and CSS fundamentalsHTML和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

  • Shaping with Angular

    用Angular打包

  • Learn Angular

    学习角度

Angular 2.x (recommended)

Angular 2.x (推荐)

  • learn Angular2 (coursetro)

    学习Angular2(coursetro )

  • YouTube playlist

    YouTube播放列表

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

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

  1. 如何在20分钟内批量部署20台ESXi服务器?

    如何在20分钟内批量部署20台ESXi服务器? https://mp.weixin.qq.com/s?__biz=MjM5NTk0MTM1Mw==&mid=2650642256&idx ...

  2. 如何在 20 分钟内给你的 K8s PaaS 上线一个新功能?

    作者 | 孙健波(天元) 来源|阿里巴巴云原生公众号 上个月,KubeVela 正式发布了, 作为一款简单易用且高度可扩展的应用管理平台与核心引擎,可以说是广大平台工程师用来构建自己的云原生 PaaS ...

  3. 服务器创建多个dhcp服务_如何在15分钟内创建无服务器服务

    服务器创建多个dhcp服务 by Charlee Li 通过李李 如何在15分钟内创建无服务器服务 (How to create a serverless service in 15 minutes) ...

  4. 如何在20分钟内找寻到生命的意义

    原文 如何找寻到你生命的真正意义?我说的不是你的工作,不是你的日常职责,也不是你的长期目标.我说的是你活着的真正原因,你为什么而存在. 也许你是一个虚无主义者,不相信你活着有一个目标,认为生活是没有意 ...

  5. 无国界医生_如何在5分钟内创建无国界风格的技能树

    无国界医生 Growing up, I spent my spare time doing what most programmers did: played video games every wa ...

  6. github创建静态页面_如何在10分钟内使用GitHub Pages创建免费的静态站点

    github创建静态页面 Static sites have become all the rage, and with good reason – they are blazingly fast a ...

  7. javascript创建类_如何在10分钟内使用JavaScript创建费用管理器

    javascript创建类 by Per Harald Borgen 通过Per Harald Borgen 如何在10分钟内使用JavaScript创建费用管理器 (How to create an ...

  8. twitter全自动发推_我如何在5分钟内自动创建FreeCodeCampers的Twitter列表

    twitter全自动发推 by Monica Powell 莫妮卡·鲍威尔(Monica Powell) 我如何在5分钟内自动创建FreeCodeCampers的Twitter列表 (How I au ...

  9. 以太坊区块链同步_以太坊69:如何在10分钟内建立完全同步的区块链节点

    以太坊区块链同步 by Lukas Lukac 卢卡斯·卢卡奇(Lukas Lukac) Ethereu M 69:如何在10分钟内建立完全同步的区块链节点 (Ethereum 69: how to ...

最新文章

  1. Linux varnish代理服务器安装以及健康检查
  2. 有向图强连通分量的三种算法
  3. jsp页面中使用超链接标签a中的属性href和onclick同时触发怎么执行
  4. 总结:数组名和指针完全是两码事
  5. 帮助孩子学会感恩_页数204_出版日期2015.03_完整版PDF电子书下载
  6. 输出绝对值(信息学奥赛一本通-T1040)
  7. 操作 Wave 文件(13): waveOutGetVolume、waveOutSetVolume
  8. es6 async函数的基本用法
  9. 谷歌返华或联手腾讯;华为否认5G专利收费;滴滴外挂让车费翻倍 | 极客头条...
  10. golang之正则校验(验证某字符串是否符合正则表达式)
  11. Python开发款短链生成器,来满足我的需求!
  12. Modern UI for WPF 初接触
  13. 训练一个图像分类器demo in PyTorch【学习笔记】
  14. 双胺基修饰MOF/GO烯复合材料|硫修饰Cu基MOF材料|磁性纳米多孔碳材料FeO@C|mof材料的复杂定制
  15. php扩展cURL执行中途无响应
  16. 分享一个免费的计算机书籍资料网站(含有编程语言,算法,人工智能,游戏开发等书籍资料)
  17. 微信小程序 JS中遍历后台获取的data数据并赋值
  18. VR全景在线虚拟展厅实现全方位沉浸式互动体验
  19. pycharm 激活码2018年9月22日亲测有效
  20. thinkpad如何屏蔽bios更新 提示电池_恢复bios出厂默认值

热门文章

  1. java开发工程师招聘软件,面试题附答案
  2. java开发工程师学什么专业,Java核心知识点
  3. 7年老Android一次操蛋的面试经历,挥泪整理面经
  4. MMKV集成与原理,赶紧学起来
  5. 意外收获字节跳动内部资料,一篇文章帮你解答
  6. 爆赞!Android岗大厂面试官常问的那些问题,论程序员成长的正确姿势
  7. java 多重属性_最全面的44个Java 性能调优细节
  8. SQL Server需要监控哪些计数器 ---指尖流淌
  9. bzoj3503: [Cqoi2014]和谐矩阵
  10. JAVA程序员面试必知32个知识点