search
HomeWeb Front-endJS TutorialAngular Development Practice (3): Analyzing Angular Component

Angular Development Practice (3): Analyzing Angular Component

Apr 02, 2018 pm 02:52 PM
angularAnalyzedevelop

This article introduces you to Angular development practice (3): Analyzing Angular Component. Interested friends can take a look at

Web Component

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

Definition

  • W3C is a unified component standard method and proposes the standard of Web Component.

  • Each component contains its own html, css, and js code.

  • Web Component standard includes the following four important concepts:

  1. Custom Elements (custom tags): Yes Create custom HTML tags and elements;

  2. ##HTML Templates: Use the

  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 an HTML document,

    .

In summary, you can create custom tags to introduce components, which is the basis of front-end componentization. References to HTML files and HTML templates on the page are used to support the writing of component views and component resources. Management, while Shadow DOM isolates code conflicts and impacts between components.

Example

Define hello-component

<template>
    <style>
        h1 {
            color: red;
        }
    </style>
    <h1 id="Hello-Web-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

nbsp;html>


    <meta>
    <meta>
    <meta>
    <meta>
    <title>Web Component</title>
    <!--导入自定义组件-->
    <link>


    <!--自定义标签-->
    <hello-component></hello-component>

As you can see from the above code, hello.html is defined according to the standard Component (named hello-component) has its own structure, style and logic. Then introduce the component file in index.html and use it 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: 'demo-component',
    template: 'Demo Component'
})
export class DemoComponent {}

  • Component decorator: Each component class must be decorated with

    @component to become an Angular component.

  • Component metadata: Component metadata:

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

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

  • 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

NameTypeFunction##animationsAnimationEntryMetadata[]changeDetectionChangeDetectionStrategyencapsulation ViewEncapsulationentryComponentsany[] interpolation[string, string]{{}}moduleIdstringstyleUrlsstring[]stylesstring[ ]templatestringtemplateUrlstringviewProvidersProvider[]

从 core/Directive 继承

Set the animation of the component
Set the component's change detection strategy
Set the component’s view packaging options
Set the list of components that will be dynamically inserted into this component view
The interpolation mark of the custom component, the default is double braces
Set the module id of this component under the ES/CommonJS specification, which is used to resolve the relative path of template styles
Set the external style file referenced by the component
Set the inline style used by the component
Setting Component’s inline template
Set the path where the component template is located
Sets the services available to the component and all its subcomponents (excluding ContentChildren)
名称 类型 作用
exportAs string 设置组件实例在模板中的别名,使得可以在模板中调用
host {[key: string]: string} 设置组件的事件、动作和属性等
inputs string[] 设置组件的输入属性
outputs string[] 设置组件的输出属性
providers Provider[] 设置组件及其所有子组件(含ContentChildren)可用的服务(依赖注入)
queries {[key: string]: any} 设置需要被注入到组件的查询
selector string 设置用于在模板中识别该组件的css选择器(组件的自定义标签)

几种元数据详解

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

inputs

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

等价于:

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

outputs

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

等价于:

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

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

等价于:

@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 使用将外部内容嵌入到组件视图后被调用,第一次ngDoCheck之后调用且只执行一次(只适用组件)。
ngAfterContentChecked ngAfterContentInit后被调用,或者每次变化监测发生时被调用(只适用组件)。
ngAfterViewInit 创建了组件的视图及其子视图之后被调用(只适用组件)。
ngAfterViewChecked ngAfterViewInit,或者每次子组件变化监测时被调用(只适用组件)。
ngOnDestroy 销毁指令/组件之前触发。此时应将不会被垃圾回收器自动回收的资源(比如已订阅的观察者事件、绑定过的DOM事件、通过setTimeout或setInterval设置过的计时器等等)手动销毁掉。

相关推荐:

Angular开发实践(一):环境准备及框架搭建

Angular开发实践(二):HRM运行机制



The above is the detailed content of Angular Development Practice (3): Analyzing 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
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function