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

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值