Angular 4 - 快速指南


Angular 4 - 概述

Angular 共有三个主要版本。发布的第一个版本是 Angular1,也称为 AngularJS。Angular1 之后是 Angular2,与 Angular1 相比,它有很多变化。

Angular 的结构基于组件/服务架构。AngularJS 基于模型视图控制器。2017 年 3 月发布的Angular 4被证明是一个重大突破,是 Angular 团队继 Angular2 之后的最新版本。

Angular 4 与 Angular 2 几乎相同。它与 Angular 2 具有向后兼容性。在 Angular 2 中开发的项目可以在 Angular 4 中正常运行。

现在让我们看看 Angular 4 中的新功能和所做的更改。

为什么是 Angular4 而不是 Angular3?

Angular 团队在其模块内部面临一些版本控制问题,由于冲突,他们不得不继续前进并发布 Angular 的下一个版本 - Angular4。

现在让我们看看 Angular 4 添加的新功能 -

ngIf

Angular2 仅支持if条件。然而,Angular 4也支持if else条件。让我们看看它如何使用 ng-template 工作。

<span *ngIf="isavailable; else condition1">Condition is valid.</span>
<ng-template #condition1>Condition is invalid</ng-template>

for循环中的as关键字

借助as关键字,您可以存储值,如下所示 -

<div *ngFor="let i of months | slice:0:5 as total">
   Months: {{i}} Total: {{total.length}}
</div>

变量total 使用as关键字存储切片的输出。

动画包

Angular 4 中的动画作为单独的包提供,需要从 @angular/animations 导入。在 Angular2 中,它可以通过 @ angular/core来使用。由于向后兼容性方面,它仍然保持不变。

模板

Angular 4使用<ng-template>作为标签而不是<template>;后者在 Angular2 中使用。Angular 4 将<template>更改为<ng-template>的原因是<template>标签与 html <template>标准标签的名称冲突。它将完全弃用。这是 Angular 4 的主要变化之一。

打字稿 2.2

Angular 4 已更新到最新版本的 TypeScript,即 2.2。这有助于提高速度并在项目中提供更好的类型检查。

管道标题案例

Angular 4 添加了新的管道标题大小写,它将每个单词的第一个字母更改为大写。

<div>
   <h2>{{ 'Angular 4 titlecase' | titlecase }}</h2>
</div>

上面的代码行生成以下输出 - Angular 4 Titlecase

HTTP 搜索参数

http get api 的搜索参数得到简化。我们不需要像 Angular2 中那样调用URLSearchParams 。

更小更快的应用程序

与 Angular2 相比,Angular 4 应用程序更小、速度更快。它使用最新版本的 TypeScript 2.2 版本,这使得最终编译的大小较小。

Angular 4 - 环境设置

在本章中,我们将讨论 Angular 4 所需的环境设置。要安装 Angular 4,我们需要以下内容 -

  • Nodejs
  • 尼普
  • 角度 CLI
  • 用于编写代码的 IDE

Nodejs 必须大于 4,npm 必须大于 3。

Nodejs

要检查您的系统上是否安装了nodejs,请在终端中输入node –v 。这将帮助您查看系统上当前安装的 Nodejs 版本。

C:\>node –v
v6.11.0

如果它没有打印任何内容,请在您的系统上安装nodejs。要安装nodejs,请进入nodejs主页https://nodejs.org/en/download/并根据您的操作系统安装软件包。

Nodejs 的主页如下所示 -

NodeJS 主页

根据您的操作系统,安装所需的软件包。一旦安装了nodejs,npm也会随之安装。要检查 npm 是否已安装,请在终端中输入 npm –v。它应该显示 npm 的版本。

C:\>npm –v
5.3.0

在 Angular CLI 的帮助下,Angular 4 安装非常简单。访问 Angular 主页https://cli.angular.io/获取命令参考。

角度 CLI

输入npm install –g @angular/cli,在您的系统上安装 Angular cli。

安装 Angular CLI

安装 Angular CLI 后,您将在终端中获得上述安装。您可以使用您选择的任何 IDE,即 WebStorm、Atom、Visual Studio Code 等。

项目设置的详细信息将在下一章中解释。

Angular 4 - 项目设置

AngularJS 基于模型视图控制器,而 Angular 2 基于组件结构。Angular 4 的工作结构与 Angular2 相同,但速度比 Angular2 更快。

Angular4 使用 TypeScript 2.2 版本,而 Angular 2 使用 TypeScript 1.8 版本。这带来了性能上的很大差异。

为了安装 Angular 4,Angular 团队提出了 Angular CLI,它简化了安装过程。您需要运行一些命令来安装 Angular 4。

转至此站点https://cli.angular.io安装 Angular CLI。

角度 CLI

要开始安装,我们首先需要确保安装了最新版本的 Nodejs 和 npm。npm 包与 nodejs 一起安装。

访问 Nodejs 站点https://nodejs.org/en/

下载 NodeJs

推荐用户使用最新版本的Nodejs v6.11.0。已经拥有大于4的nodejs的用户可以跳过上述过程。安装nodejs后,您可以使用命令node –v在命令行中检查node的版本,如下所示 -

命令提示符显示 v6.11.0

命令提示符显示 v6.11.0。一旦安装了nodejs,npm也会随之安装。

要检查 npm 的版本,请在终端中键入命令npm –v 。它将显示 npm 的版本,如下所示。

npm-v-3.10.10

npm 的版本是 3.10.10。现在我们已经安装了 Nodejs 和 npm,让我们运行 Angular cli 命令来安装 Angular 4。您将在网页上看到以下命令 -

npm install -g @angular/cli //command to install angular 4

ng new Angular 4-app // name of the project

cd my-dream-app

ng serve

让我们从命令行中的第一个命令开始,看看它是如何工作的。

首先,我们将创建一个空目录,在其中运行 Angular CLI 命令。

Angular CLI 安装步骤1

输入上述命令来安装 Angular 4。安装过程将开始,需要几分钟才能完成。

Angular CLI 安装步骤2

上述命令安装完成后,将出现以下命令提示符 -

Angular CLI 安装步骤3

我们创建了一个空文件夹ProjectA4并安装了 Angular CLI 命令。我们还使用-g全局安装 Angular CLI。现在,您可以在任何目录或文件夹中创建 Angular 4 项目,并且不必明智地安装 Angular CLI 项目,因为它全局安装在您的系统上,您可以从任何目录使用它。

现在让我们检查 Angular CLI 是否已安装。要检查安装情况,请在终端中运行以下命令 -

ng -v

Angular CLI安装步骤4

我们得到了 @angular/cli 版本,目前是 1.2.0。运行的节点版本是 6.11.0,还有操作系统详细信息。上面的详细信息告诉我们,我们已经成功安装了 Angular cli,现在我们准备开始我们的项目了。

我们现在已经安装了 Angular 4。现在让我们在 Angular 4 中创建我们的第一个项目。要在 Angular 4 中创建项目,我们将使用以下命令 -

ng new projectname

我们将项目命名为 ng new Angular 4-app

现在让我们在命令行中运行上述命令。

Angular CLI 安装步骤 5

项目Angular 4-app已成功创建。它会安装我们的项目在 Angular 4 中运行所需的所有必需包。现在让我们切换到创建的项目,该项目位于Angular 4-app目录中。在命令行中更改目录 - cd Angular 4-app

我们将使用 Visual Studio Code IDE 来处理 Angular 4;您可以使用任何 IDE,即 Atom、WebStorm 等。

要下载 Visual Studio Code,请访问https://code.visualstudio.com/并单击“下载 Windows 版”

视觉工作室代码

单击“下载 Windows 版”以安装 IDE 并运行安装程序以开始使用 IDE。

编辑器如下所示 -

Angular CLI 编辑器

我们还没有启动任何项目。现在让我们看看使用 angular-cli 创建的项目。

Angular 4 应用项目

我们将考虑Angular 4-app项目。让我们打开 Angular 4 应用程序并查看文件夹结构。

文件夹结构

现在我们已经有了项目的文件结构,让我们使用以下命令编译我们的项目 -

ng serve

ngserve命令构建应用程序并启动 Web 服务器。

ng 服务命令

ngserve 命令启动服务器

Web 服务器在端口 4200 上启动。在浏览器中键入 url http://localhost:4200/并查看输出。项目编译完成后,您将收到以下输出 -

服务器在端口 4200 上启动

在浏览器中运行http://localhost:4200/后,您将被定向到以下屏幕 -

角度应用程序

现在让我们进行一些更改以显示以下内容 -

“欢迎来到 Angular 4 项目”

Angular 4 项目

我们对文件进行了更改 - app.component.htmlapp.component.ts。我们将在后续章节中对此进行更多讨论。

让我们完成项目设置。如果您看到我们使用了端口 4200,这是 Angular-cli 在编译时使用的默认端口。如果您愿意,可以使用以下命令更改端口 -

ng serve --host 0.0.0.0 –port 4205

Angular 4 应用程序文件夹具有以下文件夹结构-

  • e2e - 端到端测试文件夹。e2e 主要用于集成测试,有助于确保应用程序正常运行。

  • node_modules - 安装的npm包是node_modules。您可以打开该文件夹并查看可用的包。

  • src - 该文件夹是我们使用 Angular 4 处理项目的位置。

Angular 4 应用程序文件夹具有以下文件结构-

  • .angular-cli.json - 它基本上包含项目名称、cli 版本等。

  • .editorconfig - 这是编辑器的配置文件。

  • .gitignore - 应将 .gitignore 文件提交到存储库中,以便与克隆存储库的任何其他用户共享忽略规则。

  • karma.conf.js - 用于通过Protractor进行单元测试。karma.conf.js 文件中提供了该项目所需的所有信息。

  • package.json - package.json 文件告诉您运行 npm install 时哪些库将安装到 node_modules 中。

目前,如果您在编辑器中打开该文件,您将看到其中添加了以下模块。

"@angular/animations": "^4.0.0",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",

如果您需要添加更多库,可以在此处添加这些库并运行 npm install 命令。

  • protractor.conf.js - 这是应用程序所需的测试配置。

  • tsconfig.json - 这基本上包含编译期间所需的编译器选项。

  • tslint.json - 这是配置文件,其中包含编译时要考虑的规则。

src文件夹是主文件夹,其内部具有不同的文件结构

应用程序

它包含下述文件。这些文件默认由 angular-cli 安装。

  • app.module.ts - 如果打开该文件,您将看到代码引用了导入的不同库。Angular-cli 使用这些默认库进行导入 – Angular/core、平台浏览器。名称本身就解释了库的用法。

它们被导入并保存到声明、导入、提供者引导等变量中。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule { }

声明- 在声明中,存储对组件的引用。App组件是每当启动新项目时创建的默认组件。我们将在不同的部分学习如何创建新组件。

导入- 这将导入如上所示的模块。目前,BrowserModule 是从 @angular/platform-b​​rowser 导入的导入的一部分。

提供者- 这将引用创建的服务。该服务将在后续章节中讨论。

bootstrap - 这引用了创建的默认组件,即 AppComponent。

  • app.component.css - 您可以在这里编写您的 css 结构。现在,我们已经向 div 添加了背景颜色,如下所示。

.divdetails{
   background-color: #ccc;
}
  • app.component.html - html 代码将在此文件中可用。

<!--The content below is only a placeholder and can be replaced.-->
<div class = "divdetails">
   <div style = "text-align:center">
      <h1>
         Welcome to {{title}}!
      </h1>
      <img width = "300" src = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNv
      ZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFe
      HBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4
      xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaH
      R0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAg
      MjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2
      ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0M
      zMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdD
      AiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMj
      MwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbn
      RzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMj
      AzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMU
      w2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMj
      UsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLD
      EzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=">
   </div>
   <h2>Here are some links to help you start: </h2>
   <ul>
      <li>
         <h2>
            <a target = "_blank" href="https://angular.io/tutorial">Tour of Heroes</a>
         </h2>
      </li>
      <li>
         <h2>
            <a target = "_blank" href = "https://github.com/angular/angular-cli/wiki">
               CLI Documentation
            </a>
         </h2>
      </li>
      <li>
         <h2>
            <a target="_blank" href="http://angularjs.blogspot.ca/">Angular blog</a>
         </h2>
      </li>
   </ul>
</div>

这是当前项目创建时可用的默认 html 代码。

  • app.component.spec.ts - 这些是自动生成的文件,其中包含源组件的单元测试。

  • app.component.ts - 组件的类在此处定义。您可以在.ts文件中对html结构进行处理。处理将包括连接数据库、与其他组件交互、路由、服务等活动。

文件的结构如下 -

import { Component } from '@angular/core';

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

资产

您可以在此文件夹中保存您的图像、js 文件。

环境

此文件夹包含生产或开发环境的详细信息。该文件夹包含两个文件。

  • 环境.产品.ts
  • 环境.ts

这两个文件都详细说明了最终文件是否应在生产环境或开发环境中编译。

Angular 4 应用程序文件夹的附加文件结构包括以下内容 -

图标.ico

该文件通常位于网站的根目录中。

索引.html

这是浏览器中显示的文件。

<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>HTTP Search Param</title>
      <base href = "/">
      <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <link href = "https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono" rel="stylesheet">
      <link href = "styles.c7c7b8bf22964ff954d3.bundle.css" rel="stylesheet">
      <meta name = "viewport" content="width=device-width, initial-scale=1">
      <link rel = "icon" type="image/x-icon" href="favicon.ico">
   </head>
   
   <body>
      <app-root></app-root>
   </body>
</html>

主体有<app-root></app-root>这是在app.component.ts文件中使用的选择器,并将显示 app.component.html 文件中的详细信息。

主要.ts

main.ts 是我们开始项目开发的文件。首先导入我们需要的基本模块。现在,如果您看到 Angular/Core、Angular/platform-b​​rowser-dynamic、app.module 和环境是在 Angular-CLI 安装和项目设置过程中默认导入的。

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);

platformBrowserDynamic ().bootstrapModule(AppModule)具有父模块引用AppModule。因此,当它在浏览器中执行时,调用的文件是index.html。Index.html 内部引用 main.ts,当以下代码执行时,它调用父模块,即 AppModule -

platformBrowserDynamic().bootstrapModule(AppModule);

当 AppModule 被调用时,它会调用 app.module.ts,后者根据 boostrap 进一步调用 AppComponent,如下所示 -

bootstrap: [AppComponent]

在app.component.ts中,有一个选择器:app-root,它在index.html文件中使用。这将显示 app.component.html 中存在的内容。

以下内容将显示在浏览器中 -

应用模块

填充.ts

这主要用于向后兼容。

样式.css

这是项目所需的样式文件。

测试.ts

在这里,将处理用于测试项目的单元测试用例。

tsconfig.app.json

这是在编译期间使用的,它具有运行应用程序所需的配置详细信息。

tsconfig.spec.json

这有助于维护测试的详细信息。

打字.d.ts

它用于管理 TypeScript 定义。

最终的文件结构如下 -

最终文件结构

Angular 4 - 组件

Angular 4 的开发的主要部分是在组件中完成的。组件基本上是与组件的 .html 文件交互的类,该文件显示在浏览器上。我们已经在前面的一章中看到了文件结构。文件结构具有应用程序组件,它由以下文件组成 -

  • 应用程序组件.css

  • 应用程序组件.html

  • 应用程序.组件.规格.ts

  • 应用程序组件.ts

  • 应用程序模块.ts

上述文件是我们使用 angular-cli 命令创建新项目时默认创建的。

如果打开app.module.ts文件,它会包含一些导入的库以及一个分配给 appcomponent 的声明,如下所示 -

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule { }

声明包括我们已经导入的 AppComponent 变量。这将成为父组件。

现在,Angular-cli 有一个命令来创建您自己的组件。但是,默认创建的应用程序组件将始终保留为父组件,而创建的下一个组件将形成子组件。

现在让我们运行命令来创建组件。

ng g component new-cmp

当您在命令行中运行上述命令时,您将收到以下输出 -

C:\projectA4\Angular 4-app>ng g component new-cmp
installing component
   create src\app\new-cmp\new-cmp.component.css
   create src\app\new-cmp\new-cmp.component.html
   create src\app\new-cmp\new-cmp.component.spec.ts
   create src\app\new-cmp\new-cmp.component.ts
   update src\app\app.module.ts

现在,如果我们检查文件结构,我们将在 src/app 文件夹下创建 new-cmp 新文件夹。

在 new-cmp 文件夹中创建以下文件 -

  • new-cmp.component.css - 创建新组件的 css 文件。

  • new-cmp.component.html - 创建 html 文件。

  • new-cmp.component.spec.ts - 这可用于单元测试。

  • new-cmp.component.ts - 在这里,我们可以定义模块、属性等。

更改将添加到 app.module.ts 文件中,如下所示 -

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
// includes the new-cmp component we created

@NgModule({
   declarations: [
      AppComponent,
      NewCmpComponent // here it is added in declarations and will behave as a child component
   ],
   imports: [
      BrowserModule
   ],
   providers: [],
   bootstrap: [AppComponent] //for bootstrap the AppComponent the main app component is given.
})

export class AppModule { }

new -cmp.component.ts文件生成如下 -

import { Component, OnInit } from '@angular/core'; // here angular/core is imported .

@Component({
   // this is a declarator which starts with @ sign. The component word marked in bold needs to be the same.
   selector: 'app-new-cmp', //
   templateUrl: './new-cmp.component.html', 
   // reference to the html file created in the new component.
   styleUrls: ['./new-cmp.component.css'] // reference to the style file.
})

export class NewCmpComponent implements OnInit {
   constructor() { }
   ngOnInit() {}
}

如果您看到上面的 new-cmp.component.ts 文件,它会创建一个名为 NewCmpComponent 的新类,该类实现 OnInit.In,它有一个构造函数和一个名为 ngOnInit() 的方法。ngOnInit 在类执行时默认被调用。

让我们检查一下流程是如何工作的。现在,默认创建的应用程序组件成为父组件。稍后添加的任何组件都将成为子组件。

当我们在http://localhost:4200/浏览器中点击 url 时,它首先执行 index.html 文件,如下所示 -

<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>Angular 4App</title>
      <base href = "/">
      <meta name="viewport" content="width = device-width, initial-scale = 1">
      <link rel = "icon" type = "image/x-icon" href = "favicon.ico">
   </head>
   
   <body>
      <app-root></app-root>
   </body>
</html>

上面是正常的html文件,我们在浏览器中看不到任何打印的内容。查看正文部分中的标签。

<app-root></app-root>

这是 Angular 默认创建的根标签。该标签在main.ts文件中具有引用。

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);

AppModule是从主父模块的app导入的,同样给bootstrap Module,这使得appmodule加载。

现在让我们看看app.module.ts文件 -

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';

@NgModule({
   declarations: [
      AppComponent,
      NewCmpComponent
   ],
   imports: [
      BrowserModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule { }

这里,AppComponent 是给定的名称,即存储应用程序引用的变量。Component.ts和 bootstrap 一样。现在让我们看看app.component.ts文件。

import { Component } from '@angular/core';

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

export class AppComponent {
   title = 'Angular 4 Project!';
}

Angular 核心被导入并称为组件,并且在声明器中使用相同的内容:

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

在对选择器的声明符引用中,给出了templateUrlstyleUrl 。这里的选择器只不过是我们上面看到的放在index.html 文件中的标签。

AppComponent 类有一个名为 title 的变量,该变量显示在浏览器中。

@Component使用名为 app.component.html 的 templateUrl 如下所示 -

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

它只有 html 代码和大括号中的变量标题。它被替换为app.component.ts文件中存在的值。这称为绑定。我们将在后续章节中讨论绑定的概念。

现在我们已经创建了一个名为new-cmp的新组件。当运行命令创建新组件时,同样的内容会包含在app.module.ts文件中。

app.module.ts具有对创建的新组件的引用。

现在让我们检查在 new-cmp 中创建的新文件。

新-cmp.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
   selector: 'app-new-cmp',
   templateUrl: './new-cmp.component.html',
   styleUrls: ['./new-cmp.component.css']
})

export class NewCmpComponent implements OnInit {
   constructor() { }
   ngOnInit() {}
}

在这里,我们也必须导入核心。组件的引用在声明符中使用。

声明器具有名为app-new-cmp 的选择器以及templateUrlstyleUrl

名为new-cmp.component.html的 .html如下 -

<p>
   new-cmp works!
</p>

如上所示,我们有 html 代码,即 p 标签。样式文件是空的,因为我们目前不需要任何样式。但是当我们运行该项目时,我们没有看到与新组件相关的任何内容显示在浏览器中。现在让我们添加一些内容,稍后可以在浏览器中看到相同的内容。

选择器,即app-new-cmp需要添加到app.component .html文件中,如下所示 -

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<app-new-cmp></app-new-cmp>

添加<app-new-cmp></app-new-cmp>标签后,创建的新组件的 .html 文件中的所有内容都将与父组件数据一起显示在浏览器上。

让我们看看新的组件 .html文件和new-cmp.component.ts文件。

新-cmp.component.ts

import { Component, OnInit } from '@angular/core';

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

export class NewCmpComponent implements OnInit {
   newcomponent = "Entered in new component created";
   constructor() {}
   ngOnInit() { }
}

在该类中,我们添加了一个名为 new component 的变量,其值为“ Entered in new component created ”。

上述变量绑定在.new-cmp.component.html文件中,如下所示 -

<p>
   {{newcomponent}}
</p>

<p>
   new-cmp works!
</p>

现在我们已经在应用程序中包含了<app-new-cmp></app-new-cmp>选择器。组件 .html是父组件的 .html,新组件 .html 文件 (new-cmp.component.html) 中的内容将显示在浏览器上,如下所示 -

使用选择器浏览器输出

同样,我们可以根据我们的要求使用app.component.html文件中的选择器创建组件并链接相同的组件。

Angular 4 - 模块

Angular 中的模块是指可以对与应用程序相关的组件、指令、管道和服务进行分组的地方。

如果您正在开发一个网站,页眉、页脚、左侧、中心和右侧部分将成为模块的一部分。

要定义模块,我们可以使用NgModule。当您使用 Angular –cli 命令创建新项目时,默认情况下会在 app.module.ts 文件中创建 ngmodule,如下所示 -

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule { }

NgModule 需要按如下方式导入 -

import { NgModule } from '@angular/core';

ngmodule 的结构如下所示 -

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})

它以@NgModule开头,包含一个具有声明、导入、提供程序和引导程序的对象。

宣言

它是创建的组件数组。如果创建任何新组件,它将首先被导入,并且引用将包含在声明中,如下所示 -

declarations: [
   AppComponent,
   NewCmpComponent
]

进口

它是应用程序中需要使用的模块数组。它也可以被声明数组中的组件使用。例如,现在在 @NgModule 中我们看到导入的浏览器模块。如果您的应用程序需要表单,您可以包含该模块,如下所示 -

import { FormsModule } from '@angular/forms';

@NgModule中的导入将如下所示 -

imports: [
   BrowserModule,
   FormsModule
]

供应商

这将包括创建的服务。

引导程序

这包括用于启动执行的主应用程序组件。

Angular 4 - 数据绑定

数据绑定可以直接从 AngularJS、Angular 2 中使用,现在也可以在 Angular 4 中使用。我们使用大括号进行数据绑定 - {{}};这个过程称为插值。我们已经在前面的示例中看到了如何将值声明为变量 title 并在浏览器中打印相同的值。

app.component.html文件中的变量被称为 {{title}} , title 的值在 app.component.ts文件中初始化,并在app.component.html中显示该值。

现在让我们在浏览器中创建月份的下拉列表。为此,我们在app.component.ts中创建了一个月份数组,如下所示 -

import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 4 Project!';
   // declared array of months.
   months = ["January", "Feburary", "March", "April", "May", 
            "June", "July", "August", "September",
            "October", "November", "December"];
}

上面显示的月份数组将显示在浏览器的下拉列表中。为此,我们将使用以下代码行 -

<!--The content below is only a placeholder and can be replaced. -->
<div style="text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select>
      <option *ngFor="let i of months">{{i}}</option>
   </select>
</div>

我们已经创建了带有选项的普通选择标签。在选项中,我们使用了for 循环。for循环用于迭代月份数组,这反过来将使用月份中存在的值创建选项标记。

Angular 中语法是*ngFor = “let I of Months”,为了获取月份值,我们将其显示在 {{i}} 中。

两个大括号有助于数据绑定。您在app.component.ts文件中声明变量,并且将使用大括号替换相同的变量。

让我们看看上面月份的数组在浏览器中的输出

在浏览器中输出月份的数组

app.component.ts中设置的变量可以使用大括号与app.component.html绑定;例如,{{}}

现在让我们根据条件在浏览器中显示数据。在这里,我们添加了一个变量并将值指定为 true。使用if语句,我们可以隐藏/显示要显示的内容。

例子

import { Component } from '@angular/core';

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

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "February", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   isavailable = true;   //variable is set to true
}

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select>
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable">Condition is valid.</span> 
   //over here based on if condition the text condition is valid is displayed. 
   If the value of isavailable is set to false it will not display the text.
</div>

输出

使用 IF 语句输出

让我们使用IF THEN ELSE条件尝试上面的示例。

例子

import { Component } from '@angular/core';

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

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "February", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   isavailable = false;
}

在本例中,我们将isavailable变量设置为 false。要打印else条件,我们必须创建 ng -template,如下所示 -

<ng-template #condition1>Condition is invalid</ng-template>

完整的代码如下所示 -

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select>
      <option *ngFor="let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf="isavailable; else condition1">Condition is valid.</span>
   <ng-template #condition1>Condition is invalid</ng-template>
</div>

If与 else 条件一起使用,使用的变量是condition1。相同的内容被分配为ng -template 的id,并且当 available 变量设置为 false 时,会显示文本Condition is invalid 。

以下屏幕截图显示了浏览器中的显示。

使用 If-Else 条件输出

现在让我们使用if then else条件。

import { Component } from '@angular/core';

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

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "February", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   isavailable = true;
}

现在,我们将变量isavailable设置为 true。在 html 中,条件按以下方式编写 -

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
   <h1>
   Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select>
      <option *ngFor="let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf="isavailable; then condition1 else condition2">Condition is valid.</span>
   <ng-template #condition1>Condition is valid</ng-template>
   <ng-template #condition2>Condition is invalid</ng-template>
</div>

如果变量为真,则条件 1,否则条件 2现在,使用 id #condition1#condition2创建了两个模板。

浏览器中的显示如下 -

使用 If-Then-Else 条件输出

Angular 4 - 事件绑定

在本章中,我们将讨论事件绑定在 Angular 4 中的工作原理。当用户以键盘移动、鼠标单击或鼠标悬停的形式与应用程序交互时,它会生成一个事件。需要处理这些事件才能执行某种操作。这就是事件绑定发挥作用的地方。

让我们考虑一个例子来更好地理解这一点。

应用程序组件.html

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select>
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable; then condition1 else condition2">
      Condition is valid.
   </span>
   <ng-template #condition1>Condition is valid</ng-template>
   <ng-template #condition2>Condition is invalid</ng-template>
</div>
<button (click)="myClickFunction($event)">
   Click Me
</button>

app.component.html文件中,我们定义了一个按钮并使用单击事件向其添加了一个函数。

以下是定义按钮并向其添加功能的语法。

(click)="myClickFunction($event)"

该函数定义在.ts文件中:app.component.ts

import { Component } from '@angular/core';

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

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "Feburary", "March", "April",
      "May", "June", "July", "August", "September",
      "October", "November", "December"];
   isavailable = true;
   myClickFunction(event) { 
      //just added console.log which will display the event details in browser on click of the button.
      alert("Button is clicked");
      console.log(event);
   }
}

单击按钮后,控件将转到函数myClickFunction并出现一个对话框,其中显示按钮被单击,如下图所示 -

使用 myClickFunction 输出

现在让我们将更改事件添加到下拉列表中。

以下代码行将帮助您将更改事件添加到下拉列表中 -

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select (change) = "changemonths($event)">
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable; then condition1 else condition2">
      Condition is valid.
   </span>
   <ng-template #condition1>Condition is valid</ng-template>
   <ng-template #condition2>Condition is invalid</ng-template>
</div>

<button (click) = "myClickFunction($event)">Click Me</button>

该函数在app.component.ts文件中声明-

import { Component } from '@angular/core';

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

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "Feburary", "March", "April",
      "May", "June", "July", "August", "September",
      "October", "November", "December"];
   isavailable = true;
   myClickFunction(event) {
      alert("Button is clicked");
      console.log(event);
   }
   changemonths(event) {
      console.log("Changed month from the Dropdown");
      console.log(event);
   }
}

控制台消息“已从下拉菜单更改月份”与事件一起显示在控制台中。

从下拉菜单更改月份

当下拉列表中的值发生更改时,让我们在app.component.ts中添加一条警报消息,如下所示 -

import { Component } from '@angular/core';

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

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "February", "March", "April",
         "May", "June", "July", "August", "September",
         "October", "November", "December"];
   
   isavailable = true;
   myClickFunction(event) { 
      //just added console.log which will display the event details in browser 
      on click of the button.
      alert("Button is clicked");
      console.log(event);
   }
   changemonths(event) {
      alert("Changed month from the Dropdown");
   }
}

当下拉列表中的值更改时,将出现一个对话框,并显示以下消息 - “从下拉列表更改月份”。

从 Dropdown2 更改月份

Angular 4 - 模板

Angular 4使用<ng-template>作为标签,而不是Angular2 中使用的<template> 。Angular 4 将<template>更改为<ng-template>的原因是<template>标签与 html <template>标准标签之间存在名称冲突。它将完全弃用。这是 Angular 4 的主要变化之一。

现在让我们将模板与if else条件一起使用并查看输出。

应用程序组件.html

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select (change) = "changemonths($event)" name = "month">
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable;then condition1 else condition2">Condition is valid.</span>
   <ng-template #condition1>Condition is valid from template</ng-template>
   <ng-template #condition2>Condition is invalid from template</ng-template>
</div>
<button (click) = "myClickFunction($event)">Click Me</button>

对于 Span 标记,我们添加了带有else条件的if语句,并将调用模板条件 1 和 else 条件 2。

模板的调用方式如下 -

<ng-template #condition1>Condition is valid from template</ng-template>
<ng-template #condition2>Condition is invalid from template</ng-template>

如果条件为真,则调用条件 1 模板,否则调用条件 2。

应用程序组件.ts

import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "February", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   isavailable = false;
   myClickFunction(event) {
      this.isavailable = false;
   }
   changemonths(event) {
      alert("Changed month from the Dropdown");
      console.log(event);
   }
}

浏览器中的输出如下 -

应用程序组件.ts 输出

变量isavailable为 false,因此打印了 condition2 模板。如果单击该按钮,将调用相应的模板。如果你检查浏览器,你会发现你永远不会在 dom 中获得 span 标签。下面的例子将帮助您理解这一点。

检查浏览器

如果你检查浏览器,你会发现 dom 没有 span 标签。它的dom模板中的条件无效。

下面这行html代码将帮助我们获取dom中的span标签。

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select (change) = "changemonths($event)" name = "month">
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable; else condition2">Condition is valid.</span>
   <ng-template #condition1>Condition is valid from template</ng-template>
   <ng-template #condition2>Condition is invalid from template</ng-template>
</div>

<button (click)="myClickFunction($event)">Click Me</button>

如果我们删除 then 条件,我们会在浏览器中收到“条件有效”消息,并且 span 标签在 dom 中也可用。例如,在app.component.ts中,我们将isavailable变量设置为 true。

app.component.ts 可用

Angular 4 - 指令

Angular 中的Directives是一个js类,声明为@directive。我们在 Angular 中有 3 个指令。下面列出了指令 -

组件指令

这些构成了主类,其中包含如何在运行时处理、实例化和使用组件的详细信息。

结构指令

结构指令主要处理 dom 元素的操作。结构指令在指令前有一个 * 符号。例如,*ngIf*ngFor

属性指令

属性指令用于更改 dom 元素的外观和Behave。您可以创建自己的指令,如下所示。

如何创建自定义指令?

在本节中,我们将讨论在组件中使用的自定义指令。自定义指令是我们创建的,不是标准的。

让我们看看如何创建自定义指令。我们将使用命令行创建指令。使用命令行创建指令的命令是 -

ng g directive nameofthedirective

e.g

ng g directive changeText

这就是它在命令行中的显示方式

C:\projectA4\Angular 4-app>ng g directive changeText
installing directive
   create src\app\change-text.directive.spec.ts
   create src\app\change-text.directive.ts
   update src\app\app.module.ts

创建上述文件,即change-text.directive.spec.tschange-text.directive.ts,并更新app.module.ts文件。

应用程序模块.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';

@NgModule({
   declarations: [
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective
   ],

   imports: [
      BrowserModule
   ],

   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule { }

ChangeTextDirective类包含在上述文件声明中。该类也是从下面给出的文件导入的。

更改文本。指示

import { Directive } from '@angular/core';
@Directive({
   selector: '[changeText]'
})

export class ChangeTextDirective {
   constructor() { }
}

上面的文件有一个指令,它还有一个选择器属性。无论我们在选择器中定义什么,它都必须在我们分配自定义指令的视图中匹配。

app.component.html视图中,我们添加指令如下 -

<div style="text-align:center">
   <span changeText >Welcome to {{title}}.</span>
</div>

我们将在change-text.directive.ts文件中写入更改,如下所示 -

更改文本.directive.ts

import { Directive, ElementRef} from '@angular/core';
@Directive({
   selector: '[changeText]'
})

export class ChangeTextDirective {
   constructor(Element: ElementRef) {
      console.log(Element);
      Element.nativeElement.innerText="Text is changed by changeText Directive. ";
   }
}

在上面的文件中,有一个名为ChangeTextDirective 的类和一个构造函数,该构造函数采用ElementRef类型的元素,这是必需的。该元素具有应用更改文本指令的所有详细信息。

我们添加了console.log元素。可以在浏览器控制台中看到相同的输出。元素的文本也发生了更改,如上所示。

现在,浏览器将显示以下内容。

更改文本指令

Angular 4 - 管道

在本章中,我们将讨论 Angular 4 中的管道是什么。管道之前在 Angular1 中称为过滤器,在 Angular 2 和 4 中称为管道。

| 的 | 字符用于转换数据。以下是相同的语法

{{ Welcome to Angular 4 | lowercase}}

它接受整数、字符串、数组和日期作为输入,并用|分隔。转换为需要的格式并在浏览器中显示。

让我们考虑一些使用管道的示例。

在这里,我们要显示大写的文本。这可以使用管道来完成,如下所示 -

app.component.ts文件中,我们定义了 title 变量 -

应用程序组件.ts

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

export class AppComponent {
   title = 'Angular 4 Project!';
}

以下代码行进入app.component.html文件。

<b>{{title | uppercase}}</b><br/>
<b>{{title | lowercase}}</b>

浏览器显示如下图所示 -

大写小写

Angular 4 提供了一些内置管道。下面列出了管道 -

  • 小写管
  • 大写管
  • 枣管
  • 货币管道
  • 杰森管道
  • 百分管
  • 十进制管道
  • 切片管

我们已经看到了小写和大写的管道。现在让我们看看其他管道是如何工作的。

以下代码行将帮助我们在app.component.ts文件中定义所需的变量 -

import { Component } from '@angular/core';

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

export class AppComponent {
   title = 'Angular 4 Project!';
   todaydate = new Date();
   jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}};
   months = ["Jan", "Feb", "Mar", "April", "May", "Jun",
             "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
}

我们将使用app.component.html文件中的管道。

<!--The content below is only a placeholder and can be replaced.-->
<div style = "width:100%;">
   <div style = "width:40%;float:left;border:solid 1px black;">
      <h1>Uppercase Pipe</h1>
      <b>{{title | uppercase}}</b><br/>
      
      <h1>Lowercase Pipe</h1>
      <b>{{title | lowercase}}</b>
      
      <h1>Currency Pipe</h1>
      <b>{{6589.23 | currency:"USD"}}</b><br/>
      <b>{{6589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency.
      
      <h1>Date pipe</h1>
      <b>{{todaydate | date:'d/M/y'}}</b><br/>
      <b>{{todaydate | date:'shortTime'}}</b>
      
      <h1>Decimal Pipe</h1>
      <b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed.
   </div>
   
   <div style = "width:40%;float:left;border:solid 1px black;">
      <h1>Json Pipe</h1>
      <b>{{ jsonval | json }}</b>
      <h1>Percent Pipe</h1>
      <b>{{00.54565 | percent}}</b>
      <h1>Slice Pipe</h1>
      <b>{{months | slice:2:6}}</b> 
      // here 2 and 6 refers to the start and the end index
   </div>
</div>

以下屏幕截图显示了每个管道的输出 -

每个管道的输出

每个 Pipe-2 的输出

如何创建自定义管道?

为了创建自定义管道,我们创建了一个新的ts文件。在这里,我们要创建sqrt自定义管道。我们为该文件指定了相同的名称,如下所示 -

应用程序.sqrt.ts

import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
   name : 'sqrt'
})
export class SqrtPipe implements PipeTransform {
   transform(val : number) : number {
      return Math.sqrt(val);
   }
}

要创建自定义管道,我们必须从 Angular/core 导入 Pipe 和 Pipe Transform。在 @Pipe 指令中,我们必须为管道指定名称,该名称将在 .html 文件中使用。由于我们正在创建 sqrt 管道,因此我们将其命名为 sqrt。

当我们继续进行时,我们必须创建该类,类名称为SqrtPipe<