Home Web Front-end JS Tutorial Detailed explanation of Angular Component use cases

Detailed explanation of Angular Component use cases

May 03, 2018 pm 03:09 PM
angular component Detailed explanation

This time I will bring you a detailed explanation of the use cases of Angular Component. What are the precautions when using Angular Component? The following is a practical case, let's take a look.

Web Component

Before introducing Angular Component, let’s briefly understand W3C Web Components

Definition

W3C proposes the standard of Web Component to unify the standard way of componentization.

Each component contains its own html, css, and js code.
Web Component standard includes the following four important concepts:
1.Custom Elements (custom tags): You can create custom HTML tags and elements;
2.HTML Templates (HTML templates): use < ;template> tag to predefine some content, but it does not load it into the page, but uses JS code to initialize it;
3.Shadow DOM (virtual DOM): You can create a DOM subtree that is completely independent from other elements;
4.HTML Imports: A method of introducing other HTML documents into HTML documents, .

In summary, the ability to create custom tags to introduce components is the basis for front-end componentization. References to HTML files and HTML templates on the page are used to support writing component views and component resource management, while Shadow DOM It is to isolate the conflicts and impacts of code between components.

Example

Define hello-component

<template id="hello-template">
  <style>
    h1 {
      color: red;
    }
  </style>
  <h1>Hello Web Component!</h1>
</template>
<script>
  // 指向导入文档,即本例的index.html
  var indexDoc = document;
  // 指向被导入文档,即当前文档hello.html
  var helloDoc = (indexDoc._currentScript || indexDoc.currentScript).ownerDocument;
  // 获得上面的模板
  var tmpl = helloDoc.querySelector('#hello-template');
  // 创建一个新元素的原型,继承自HTMLElement
  var HelloProto = Object.create(HTMLElement.prototype);
  // 设置 Shadow DOM 并将模板的内容克隆进去
  HelloProto.createdCallback = function() {
    var root = this.createShadowRoot();
    root.appendChild(indexDoc.importNode(tmpl.content, true));
  };
  // 注册新元素
  var hello = indexDoc.registerElement('hello-component', {
    prototype: HelloProto
  });
</script>
Copy after login

Use hello-component

<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="author" content="赖祥燃, laixiangran@163.com, http://www.laixiangran.cn"/>
  <title>Web Component</title>
  <!--导入自定义组件-->
  <link rel="import" href="hello.html" rel="external nofollow" >
</head>
<body>
  <!--自定义标签-->
  <hello-component></hello-component>
</body>
</html>
Copy after login

As you can see from the above code, hello. html is a component defined by standards (named hello-component). This component has its own structure, style and logic. Then introduce the component file in index.html and use it like an ordinary tag.

Angular Component

Angular Component is a type of directive and can be understood as a directive with a template. The other two types are attribute directives and structural directives.

Basic composition

@Component({
  selector: 'demo-component',
  template: 'Demo Component'
})
export class DemoComponent {}
Copy after login
  1. Component decorator: Each component class must be decorated with @component to become an Angular component.

  2. Component metadata: Component metadata: selector, template, etc. The following will focus on the meaning of each metadata.

  3. Component class: Component is actually an ordinary class, and the logic of the component is defined and implemented in the component class.

  4. Component template: Each component will be associated with a template, which will eventually be rendered on the page. The DOM element on the page is the host element of this component instance.

Component metadata

Self metadata attributes

##animationsAnimationEntryMetadata[]Set the animation of the componentchangeDetectionChangeDetectionStrategySet the change detection strategy of the component##encapsulationentryComponentsinterpolationmoduleIdstyleUrlsstylestemplatetemplateUrlviewProviders

Inherited from core/Directive

Name Type Function
ViewEncapsulation Set the view packaging options of the component
any[] Set the list of components that will be dynamically inserted into the component view
[string, string] Interpolation mark of custom component, the default is double curly brackets
string Set the module id of the component under the ES/CommonJS specification, which is used to resolve the relative path of the template style
string[] Set the external style file referenced by the component
string[] Set the inline style used by the component
string Set the inline template of the component
string Set the path to the component template
Provider[] Set the services available to the component and all its subcomponents (excluding ContentChildren)
##NameTypeFunction##exportAshostinputsoutputsprovidersDependency Injectionqueries selectorcss selector

几种元数据详解

以下几种元数据的等价写法会比元数据设置更简洁易懂,所以一般推荐的是等价写法。

inputs

@Component({
  selector: 'demo-component',
  inputs: ['param']
})
export class DemoComponent {
  param: any;
}
Copy after login

等价于:

@Component({
  selector: 'demo-component'
})
export class DemoComponent {
  @Input() param: any;
}
Copy after login

outputs

@Component({
  selector: 'demo-component',
  outputs: ['ready']
})
export class DemoComponent {
  ready = new eventEmitter<false>();
}
Copy after login

等价于:

@Component({
  selector: 'demo-component'
})
export class DemoComponent {
  @Output() ready = new eventEmitter<false>();
}
Copy after login

host

@Component({
  selector: 'demo-component',
  host: {
    '(click)': 'onClick($event.target)', // 事件
    'role': 'nav', // 属性
    '[class.pressed]': 'isPressed', // 类
  }
})
export class DemoComponent {
  isPressed: boolean = true;
  onClick(elem: HTMLElement) {
    console.log(elem);
  }
}
Copy after login

等价于:

@Component({
  selector: 'demo-component'
})
export class DemoComponent {
  @HostBinding('attr.role') role = 'nav';
  @HostBinding('class.pressed') isPressed: boolean = true;
 
  @HostListener('click', ['$event.target'])
  onClick(elem: HTMLElement) {
    console.log(elem);
  }
}
Copy after login

queries - 视图查询

@Component({
  selector: 'demo-component',
  template: `
    <input #theInput type=&#39;text&#39; />
    <p>Demo Component</p>
  `,
  queries: {
    theInput: new ViewChild('theInput')
  }
})
export class DemoComponent {
  theInput: ElementRef;
}
Copy after login

等价于:

@Component({
  selector: 'demo-component',
  template: `
    <input #theInput type=&#39;text&#39; />
    <p>Demo Component</p>
  `
})
export class DemoComponent {
  @ViewChild('theInput') theInput: ElementRef;
}
Copy after login

queries - 内容查询

<my-list>
  <li *ngFor="let item of items;">{{item}}</li>
</my-list>
Copy after login
@Directive({
  selector: 'li'
})
export class ListItem {}
Copy after login
@Component({
  selector: 'my-list',
  template: `
    <ul>
      <ng-content></ng-content>
    </ul>
  `,
  queries: {
    items: new ContentChild(ListItem)
  }
})
export class MyListComponent {
  items: QueryList<ListItem>;
}
Copy after login

等价于:

@Component({
  selector: 'my-list',
  template: `
    <ul>
      <ng-content></ng-content>
    </ul>
  `
})
export class MyListComponent {
  @ContentChild(ListItem) items: QueryList<ListItem>;
}
Copy after login

styleUrls、styles

styleUrls和styles允许同时指定。

优先级:模板内联样式 > styleUrls > styles。

建议:使用styleUrls引用外部样式表文件,这样代码结构相比styles更清晰、更易于管理。同理,模板推荐使用templateUrl引用模板文件。

changeDetection

ChangeDetectionStrategy.Default:组件的每次变化监测都会检查其内部的所有数据(引用对象也会深度遍历),以此得到前后的数据变化。

ChangeDetectionStrategy.OnPush:组件的变化监测只检查输入属性(即@Input修饰的变量)的值是否发生变化,当这个值为引用类型(Object,Array等)时,则只对比该值的引用。

显然,OnPush策略相比Default降低了变化监测的复杂度,很好地提升了变化监测的性能。如果组件的更新只依赖输入属性的值,那么在该组件上使用OnPush策略是一个很好的选择。

encapsulation

ViewEncapsulation.None:无 Shadow DOM,并且也无样式包装。

ViewEncapsulation.Emulated:无 Shadow DOM,但是通过Angular提供的样式包装机制来模拟组件的独立性,使得组件的样式不受外部影响,这是Angular的默认设置。

ViewEncapsulation.Native:使用原生的 Shadow DOM 特性。

生命周期

当Angular使用构造函数新建组件后,就会按下面的顺序在特定时刻调用这些生命周期钩子方法:

string Set the alias of the component instance in the template so that it can be called in the template
{[key: string]: string} Set the events, actions and properties of the component
string[] Set the input properties of the component
string[] Set the output properties of the component
Provider[] Set the services available to the component and all its subcomponents (including ContentChildren) ()
{[key: string]: any} Set the queries that need to be injected into the component
string Set the (custom label of the component) used to identify this component in the template
生命周期钩子 调用时机
ngOnChanges 在ngOnInit之前调用,或者当组件输入数据(通过@Input装饰器显式指定的那些变量)变化时调用。
ngOnInit 第一次ngOnChanges之后调用。建议此时获取数据,不要在构造函数中获取。
ngDoCheck 每次变化监测发生时被调用。
ngAfterContentInit 使用
ngAfterContentChecked ngAfterContentInit后被调用,或者每次变化监测发生时被调用(只适用组件)。
ngAfterViewInit 创建了组件的视图及其子视图之后被调用(只适用组件)。
ngAfterViewChecked ngAfterViewInit,或者每次子组件变化监测时被调用(只适用组件)。
ngOnDestroy 销毁指令/组件之前触发。此时应将不会被垃圾回收器自动回收的资源(比如已订阅的观察者事件、绑定过的DOM事件、通过setTimeout或setInterval设置过的计时器等等)手动销毁掉。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue里调用百度地图步骤详解

vue中如何使用jointjs属性

The above is the detailed content of Detailed explanation of Angular Component use cases. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of the mode function in C++ Detailed explanation of the mode function in C++ Nov 18, 2023 pm 03:08 PM

Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of remainder function in C++ Detailed explanation of remainder function in C++ Nov 18, 2023 pm 02:41 PM

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Interviewer: The difference between @Configuration and @Component Interviewer: The difference between @Configuration and @Component Aug 15, 2023 pm 04:29 PM

Calling the @Bean annotated method in the @Configuration class returns the same example; calling the @Bean annotated method in the @Component class returns a new instance.

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

See all articles