Home >Web Front-end >JS Tutorial >Angular Components: A Comprehensive Guide for Beginners
Building single-page applications is an art, and there are many impressive frameworks to choose from. Angular is one of the most intuitive and widely used frameworks for building web and mobile applications. Today, Angular 10 has been released, and it comes with a lot of impressive features. Before you dig deeper, however, you need to master the components.
Before trying Angular, you need to make sure you have successfully installed the following dependencies:
You can install Angular CLI globally using NPM.
npm install -g @angular/cli
Now you can start your Angular project in a few different ways:
Here's how to create a new project using Angular CLI:
ng new my-project-name cd my-project-name
That's it! Now your Angular journey has begun. In this article, we will build a simple calculator for adding two numbers using Angular.
In Angular, we use directives. There are three types of directives: structural directives, attribute directives and component directives. In the next few sections, we'll dive into everything about components.
Components in Angular are the elements we design and build for rendering UI projects. These UI items will allow users to interact with the application and access its functionality.By the end of this tutorial, you will be able to build components in Angular. What's more, you'll understand every step of the way.
Components will be available in any Angular project from day one. In a way, you can think of any Angular project as a tree made up of many connected components. Each component has a specific functionality and a template that renders it. A single template can be reused in multiple components. A collection of components forms an Angular application, which is ultimately seen in the browser.
A component is like a class that encapsulates the behavior of an element and its view. Behavior includes the data that is loaded or rendered and how the user interacts with it, and its views are templates that define how the data is presented.
Let's learn about components by creating an Angular component for adding two numbers. We won't be creating the components step by step in this tutorial, but you can find the complete code for this application in our GitHub repository.
Component
decorator to define componentsComponent
Decorators are used to define components in Angular. The metadata that defines the component is as follows:
@Component({ selector: 'calculator', templateUrl: './calculator.component.html', styleUrls: ['./calculator.component.css'] }) export class Calculator{ }
In the definition above, selector
tells the application which elements of the application's HTML the component needs to be used for. templateUrl
Tells the application what can be rendered. Everything else in the above decorator is optional.
selector
is an important property in Angular. It helps the application determine where to place components. The selector is always a string. Selectors can be defined in three different ways, each with unique use cases:
selector: 'calculator'
Can be used when the component will be specified as a <calculator></calculator>
element in HTML. selector: '.calculator'
If the component is to be used as a CSS element, it can be used
in HTML. selector: '[calculator]'
Can be used when the component should be used as a property, it looks like
.Selectors can be simple or complex, but the golden rule is to keep the selector as simple as possible.
templateUrl
Identifies the template that the component will use. The path to the template should be relative. For templates located in the same folder as the component source code, you can use templateUrl: './calculator.html'
or templateUrl: 'calculator.html'
.
You also have the option of using the template
option to replace the templateUrl
option with an inline template. This is useful in simple components where the TypeScript code and HTML don't have to be in different files.
This approach has no impact on the final application. Why? Regardless of the method, a single bundle is generated.
styleUrl
? Components are never simple; they are always full of styles. The styleUrl
property is used to help you include component-specific CSS. Just like templates, you can use inline styles via the styles
attribute. But if the code has a lot of styles, it needs to be separated into different files.
Note that styleUrl
always takes an array, so you can add multiple stylesheets.
Angular 组件始终鼓励样式隔离和完整封装。这意味着子组件或父组件中的样式不会影响 UI 层次结构中的其他组件。
为了控制样式封装,Angular 在 Component
装饰器中提供了一个名为 encapsulation
的属性。封装可以具有以下值之一:
ViewEncapsulation.Emulated
是默认值。它创建填充样式来模拟影子根和 DOM。ViewEncapsulation.ShadowDom
是最快的。 ViewEncapsulation.None
,正如其名称所示,使用全局样式并避免任何形式的封装。 在我们的计算器组件中使用 encapsulation
属性的语法如下:
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'calculator', templateUrl: './calculator.component.html', styleUrls: ['./calculator.component.css'], encapsulation: ViewEncapsulation.None }) export class Calculator{}
在上面的示例中,我们选择了 ViewEncapsulation.None
。这绝对是将通用样式应用于父组件和子组件的最佳方式。
在深入了解组件生命周期之前,让我们先看看组件和模块是如何相互链接的。我们的计算器应用程序的模块如下:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { CalcComponent } from './calc/calc.component' @NgModule({ declarations: [ AppComponent, CalcComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
如果您创建组件,则必须将其包含为模块的一部分。
如果不将新创建的组件添加到模块中,则会出现错误。
要将组件添加到模块,必须首先导入它。首先,必须将导入的文件添加到 declarations
数组中。现在,该组件在整个应用程序中都是可见的,并且可以被其他组件使用。
让我们看看 @NgModule
指令中的每个数组代表什么:
declarations
确保指令和组件在模块的范围内可用。 Angular CLI 具有一项功能,可以将指令和组件自动添加到模块中。imports
用于导入和访问其他模块。这允许开发人员在应用程序中包含第三方模块。 exports
。如果组件未导出,则无法在其他地方使用。 我们现在准备了解组件和指令的生命周期。请记住,每个组件都有一个生命周期,从创建到销毁。渲染组件的那一刻,该组件及其子组件的生命周期就开始了。
了解生命周期事件在 Angular 应用程序中非常有用,它可以帮助开发人员正确观察和响应事件。
以下是 Angular 组件的生命周期挂钩,按照调用每个挂钩的顺序排列。
ngOnChanges
ngOnInit
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngAfterViewInit
ngAfterViewChecked
ngOnDestroy
创建组件时,会调用 构造函数
。接下来,按照上述顺序调用各种钩子。某些挂钩(例如 OnInit
和 AfterContentInit
)将仅被调用一次。同时,只要组件中的内容发生更改,就会调用其他挂钩。最后,onDestroy
被调用一次。
上面的生命周期钩子有一个接口。要使用钩子,您应该实现该接口。通常,该接口带有函数,以 ng
开头。例如,如果要使用 ngOnInit
函数,则组件必须实现 OnInit
接口。以下是 Angular 组件中生命周期挂钩中常用接口和方法的快速摘要。该表再次根据实现时首先调用的方法进行排序。
界面 | 方法 | 目的 |
OnChanges |
ngOnChanges |
在构造函数之后以及输入值发生更改时调用。 |
OnInit |
ngOnInit |
仅调用一次。非常特定于组件或指令。它是从服务器加载数据的最佳位置。 |
DoCheck |
ngDoCheck |
当 Angular 无法自动检查更改或绑定时,使用此方法。它通知组件任何变化。 |
AfterContentInit |
ngAfterContentInit |
仅调用一次。它由组件初始化触发。 |
AfterContentChecked |
ngAfterContentChecked |
在组件内容的每次更改时调用。 |
AfterViewInit |
ngAfterViewInit |
一旦每个子组件都被初始化,就会调用这个生命周期钩子。视图可能没有完全渲染,但内部视图已经由 Angular 准备好了。 |
AfterViewChanged |
ngAfterViewChecked |
一旦每个子组件都经过验证和更新,就会调用此挂钩。 |
OnDestroy |
ngOnDestroy |
如果组件准备好从 UI 中删除或销毁,则会调用此挂钩。这是保留取消订阅和取消注册可观察对象或计时器的侦听器的好地方。 |
现在,如果您想将生命周期挂钩添加到我们的计算器组件中,它将显示如下:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'calculator', templateUrl: './calculator.component.html', styleUrls: ['./calculator.component.css'], encapsulation: ViewEncapsulation.None }) export class Calculator implements OnInit { constructor() {} ngOnInit(): void { console.log('Component - On Init'); } }
我们正在构建的计算器应用程序的 UI 如下所示。
这是我们将添加到组件模板中的 HTML:
<div class="row"> <div class="col-12"> <input [(ngModel)]="number1" type="number" name="" placeholder="number"> </div> </div> <div class="row"> <div class="col-12"> <input [(ngModel)]="number2" type="number" name="" placeholder="number"> </div> </div> <button (click)="add()" class="button"> Add </button> <div class="result"> <span> Result : {{result}} </span> </div>
UI呈现后,用户将对应用程序执行操作。现在,应用程序必须做出相应的响应。例如,当用户输入两个数字并单击添加时,我们的计算器必须进行添加。使用此功能连接输入框的最简单方法是通过 ngModel
。在 HTML 模板文件中,每个输入都可以链接到 ngModel
变量。您可以在上面的 HTML 中看到,我们有许多 ngModel
属性将 HTML 元素链接到我们的 TypeScript 代码。这些变量将在计算器组件源代码中声明和使用。
让我们看看如何在计算器的 TypeScript 代码中使用 ngModel
变量。
//the component import { Component } from '@angular/core'; @Component({ selector: 'calc', templateUrl: 'calc.component.html', styleUrls: ['calc.component.css'] }) export class CalcComponent { public number1 : number; public number2 : number; public result : number; public add(){ this.result = this.number1 + this.number2 } }
每次用户在输入框中输入值时,this.number1
和 this.number2
都会相应更新。为什么? ngModel
用于捕获输入。
当用户点击添加按钮时,将调用 add
函数。如何?我们利用 (click)
控件将按钮连接到 add
方法。
当调用 add
时,this.result
根据 this.number1
和 this.number2
进行更新。一旦 this.result
更新,UI 也会更新。如何? {{result}}
链接到 this.result
。
我希望本教程有用。现在,您应该了解 Angular 组件的基础知识。您刚刚了解了如何定义组件、利用各种生命周期挂钩,以及最终进行用户交互。这仅仅是个开始。 Angular 组件还有很多东西。
本教程中功能齐全的源代码可在 GitHub 上获取。看一看,并尝试创建您自己的 Angular 项目 - 这是最好的学习方式!
The above is the detailed content of Angular Components: A Comprehensive Guide for Beginners. For more information, please follow other related articles on the PHP Chinese website!