search
HomeWeb Front-endJS TutorialAnalyzing the source code examples of Angular Component
Analyzing the source code examples of Angular ComponentMay 26, 2018 pm 03:43 PM
angularcomponentExample

This article mainly introduces the source code examples of analyzing Angular Component. Now I share it with you and give you a reference.

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 id="Hello-nbsp-Web-nbsp-Component">Hello Web Component!</h1>
</template>

<script>

  // 指向导入文档,即本例的index.html
  var indexDoc = document;

  // 指向被导入文档,即当前文档hello.html
  var helloDoc = (indexDoc._currentScript || indexDoc.currentScript).ownerDocument;

  // 获得上面的模板
  var tmpl = helloDoc.querySelector(&#39;#hello-template&#39;);

  // 创建一个新元素的原型,继承自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(&#39;hello-component&#39;, {
    prototype: HelloProto
  });
</script>

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>

As you can see from the above code, hello.html is a component defined according to standards (named hello-component). This component has its own structure, style and logic, and then introduce the component file in index.html, and it can be used like a normal 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: &#39;demo-component&#39;,
  template: &#39;Demo Component&#39;
})
export class DemoComponent {}

  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


Name TypeFunctionanimationsAnimationEntryMetadata[]Setting component AnimationchangeDetectionChangeDetectionStrategySet the component’s change detection strategyencapsulationViewEncapsulationSet the component's view packaging optionsentryComponentsany[]The settings will be dynamically inserted into Component list in this component viewinterpolation[string, string]Interpolation mark of custom component, the default is double curly bracketsmoduleIdstringSet the module id of the component under the ES/CommonJS specification, which is used to resolve the relative path of template stylesstyleUrlsstring[]Set the external style file referenced by the componentstylesstring[]Set the inline style used by the componenttemplatestringSet the inline template of the component templateUrlstringSet the path to the component templateviewProviders Provider[]Sets the services available to the component and all its subcomponents (excluding ContentChildren)
Inherits from core/Directive


NameTypeFunctionexportAsstringSet the alias of the component instance in the template so that it can be called in the templatehost{ [key: string]: string}Set the events, actions and properties of the componentinputsstring[]Set the input properties of the componentoutputsstring[]Set the output properties of the componentprovidersProvider[]Set the services (dependency injection) available to the component and all its subcomponents (including ContentChildren)queries{[key: string]: any}Set the query that needs to be injected into the componentselectorstringSet the css selector (custom label of the component) used to identify the component in the template

几种元数据详解

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

inputs

@Component({
  selector: &#39;demo-component&#39;,
  inputs: [&#39;param&#39;]
})
export class DemoComponent {
  param: any;
}

等价于:

@Component({
  selector: &#39;demo-component&#39;
})
export class DemoComponent {
  @Input() param: any;
}

outputs

@Component({
  selector: &#39;demo-component&#39;,
  outputs: [&#39;ready&#39;]
})
export class DemoComponent {
  ready = new eventEmitter<false>();
}

等价于:

@Component({
  selector: &#39;demo-component&#39;
})
export class DemoComponent {
  @Output() ready = new eventEmitter<false>();
}

host

@Component({
  selector: &#39;demo-component&#39;,
  host: {
    &#39;(click)&#39;: &#39;onClick($event.target)&#39;, // 事件
    &#39;role&#39;: &#39;nav&#39;, // 属性
    &#39;[class.pressed]&#39;: &#39;isPressed&#39;, // 类
  }
})
export class DemoComponent {
  isPressed: boolean = true;

  onClick(elem: HTMLElement) {
    console.log(elem);
  }
}

等价于:

@Component({
  selector: &#39;demo-component&#39;
})
export class DemoComponent {
  @HostBinding(&#39;attr.role&#39;) role = &#39;nav&#39;;
  @HostBinding(&#39;class.pressed&#39;) isPressed: boolean = true;

 
  @HostListener(&#39;click&#39;, [&#39;$event.target&#39;])
  onClick(elem: HTMLElement) {
    console.log(elem);
  }
}

queries - 视图查询

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

等价于:

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

queries - 内容查询

<my-list>
  <li *ngFor="let item of items;">{{item}}</li>
</my-list>

@Directive({
  selector: &#39;li&#39;
})
export class ListItem {}

@Component({
  selector: &#39;my-list&#39;,
  template: `
    <ul>
      <ng-content></ng-content>
    </ul>
  `,
  queries: {
    items: new ContentChild(ListItem)
  }
})
export class MyListComponent {
  items: QueryList<ListItem>;
}

等价于:

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

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使用构造函数新建组件后,就会按下面的顺序在特定时刻调用这些生命周期钩子方法:


生命周期钩子 调用时机
ngOnChanges 在ngOnInit之前调用,或者当组件输入数据(通过@Input装饰器显式指定的那些变量)变化时调用。
ngOnInit 第一次ngOnChanges之后调用。建议此时获取数据,不要在构造函数中获取。
ngDoCheck 每次变化监测发生时被调用。
ngAfterContentInit 使用
ngAfterContentChecked ngAfterContentInit后被调用,或者每次变化监测发生时被调用(只适用组件)。
ngAfterViewInit 创建了组件的视图及其子视图之后被调用(只适用组件)。
ngAfterViewChecked ngAfterViewInit,或者每次子组件变化监测时被调用(只适用组件)。
ngOnDestroy 销毁指令/组件之前触发。此时应将不会被垃圾回收器自动回收的资源(比如已订阅的观察者事件、绑定过的DOM事件、通过setTimeout或setInterval设置过的计时器等等)手动销毁掉。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Ajax发送和接收二进制字节流数据的方法

laypage前端分页插件实现ajax异步分页

ajax文件上传成功 解决浏览器兼容问题

The above is the detailed content of Analyzing the source code examples of Angular Component. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
聊聊Angular中的元数据(Metadata)和装饰器(Decorator)聊聊Angular中的元数据(Metadata)和装饰器(Decorator)Feb 28, 2022 am 11:10 AM

本篇文章继续Angular的学习,带大家了解一下Angular中的元数据和装饰器,简单了解一下他们的用法,希望对大家有所帮助!

angular学习之详解状态管理器NgRxangular学习之详解状态管理器NgRxMay 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

项目过大怎么办?如何合理拆分Angular项目?项目过大怎么办?如何合理拆分Angular项目?Jul 26, 2022 pm 07:18 PM

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

Angular + NG-ZORRO快速开发一个后台系统Angular + NG-ZORRO快速开发一个后台系统Apr 21, 2022 am 10:45 AM

本篇文章给大家分享一个Angular实战,了解一下angualr 结合 ng-zorro 如何快速开发一个后台系统,希望对大家有所帮助!

聊聊Angular Route中怎么提前获取数据聊聊Angular Route中怎么提前获取数据Jul 13, 2022 pm 08:00 PM

Angular Route中怎么提前获取数据?下面本篇文章给大家介绍一下从 Angular Route 中提前获取数据的方法,希望对大家有所帮助!

vue3怎么使用defineAsyncComponent与component标签实现动态渲染组件vue3怎么使用defineAsyncComponent与component标签实现动态渲染组件May 12, 2023 pm 05:55 PM

一、基础的动态引入组件:简单的动态引入的意思是,前端知道要引入哪些组件,将多个组件引入到父组件中,但不渲染它,满足一定条件后,才去在某个位置渲染指定的组件。import{reactive,ref,shallowReactive,onActivated,defineAsyncComponent,}from&#39;vue&#39;;constcustomModal=defineAsyncComponent(()=>import(&#39;./modal/CustomM

浅析Angular中的独立组件,看看怎么使用浅析Angular中的独立组件,看看怎么使用Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

Angular的:host、:host-context、::ng-deep选择器Angular的:host、:host-context、::ng-deep选择器May 31, 2022 am 11:08 AM

本篇文章带大家深入了解一下angular中的几个特殊选择器:host、:host-context、::ng-deep,希望对大家有所帮助!

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools