angular 自定义组件_如何创建Angular 6自定义元素和Web组件

 2023-09-06 阅读 25 评论 0

摘要:angular 自定义组件by Prateek Mishra 通过Prateek Mishra 如何创建Angular 6自定义元素和Web组件 (How to create Angular 6 Custom Elements and Web Components) 使用Angular CLI创建Angular元素的6个步骤 (6 Steps to create Angular elements using Angular CLI) Angular

angular 自定义组件

by Prateek Mishra

通过Prateek Mishra

如何创建Angular 6自定义元素和Web组件 (How to create Angular 6 Custom Elements and Web Components)

使用Angular CLI创建Angular元素的6个步骤 (6 Steps to create Angular elements using Angular CLI)

Angular elements are Angular components that carry the minified version of the whole framework. They allow you to create custom elements (one of the web components) in a framework-agnostic way. They can be used in simple web projects but with the powers of Angular within.

Angular元素是Angular组件,带有整个框架的缩小版本。 它们允许您以与框架无关的方式创建自定义元素 (Web组件之一)。 它们可以用于简单的Web项目中,但可以使用Angular的功能。

After reading the official documentation for Angular elements I realized that it lacks the implementation part in a structured manner. That is the reason I am stating the steps to get going!

阅读有关Angular元素的官方文档后 ,我意识到它缺乏结构化的实现部分。 这就是我要说明要采取的步骤的原因!

1.安装Angular CLI 6并创建一个新项目 (1. Install Angular CLI 6 and create a new project)

npm i -g @angular/cling new angular-custom-elements

As Angular introduced the concept of custom elements in Angular 6 we must have v6 or later installed. You can also add the--style flag to set the default style extension.

当Angular在Angular 6中引入自定义元素的概念时,我们必须安装v6或更高版本。 您还可以添加--style标志以设置默认样式扩展名。

2.添加元素包 (2. Add elements package)

Custom elements are not completely implemented by all the browsers. Hence we require Polyfills to get them working. With the new CLI command ng add you can add the Angular library and the required polyfills:

并非所有浏览器都完全实现自定义元素。 因此,我们要求Polyfills使它们起作用。 使用新的CLI命令ng add您可以添加Angular库和所需的polyfills:

ng add @angular/elements

3.创建一个组件 (3. Create a component)

Let’s create a component that will act as a custom element by the end of this post:

让我们创建一个在本文结尾处将用作自定义元素的组件:

ng g component button --inline-style --inline-template -v Native

We are using ViewEncapsulation.Native to prevent the styles of component from bleeding out and affect other elements. This will render our component in browser’s native implementation of shadow DOM (v0; for v1 we use ViewEncapsulation.ShadowDOM) by bundling all the styles, template and component class code in a single file.

我们使用ViewEncapsulation.Native来防止组件样式ViewEncapsulation.Native并影响其他元素。 通过将所有样式,模板和组件类代码捆绑在一个文件中,这将使我们的组件呈现在浏览器的本机影子DOM实现中(v0;对于v1,我们使用ViewEncapsulation.ShadowDOM )。

4.向组件添加属性 (4. Add properties to the component)

After making a few changes our button component looks like:

进行一些更改后,我们的按钮组件如下所示:

According to the official docs:

根据官方文档:

The creation API parses the component looking for input properties, and defines corresponding attributes for the custom element.

创建API解析组件以查找输入属性,并为custom元素定义相应的属性。

The creation API parses the component looking for input properties, and defines corresponding attributes for the custom element.

创建API解析组件以查找输入属性,并为custom元素定义相应的属性。

It transforms the property names to make them compatible with custom elements, which do not recognize case distinctions. The resulting attribute names use dash-separated lowercase. For example, for a component with @Input('myInputProp') inputProp, the corresponding custom element defines an attribute ‘‘my-input-prop”.

它将转换属性名称,使其与不区分大小写的自定义元素兼容。 结果属性名称使用短划线分隔的小写字母。 例如,对于具有@Input('myInputProp') inputProp ,相应的自定义元素定义属性“ my-input-prop”

And also:

并且:

Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name.

组件输出作为HTML Custom Events调度,其自定义事件的名称与输出名称匹配。

Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name.

组件输出作为HTML Custom Events调度,其自定义事件的名称与输出名称匹配。

For example, for a component with @Output() valueChanged = new EventEmitter(), the corresponding custom element will dispatch events with the name "valueChanged". The emitted data will be stored on the event’s detail property. If you provide an alias, that value is used. For example, @Output('myClick') clicks = new EventEmitter<string&gt;(); results in dispatch events with the name "myClick".

例如,对于具有@Output() valueChanged = new EventEmitter() ,相应的自定义元素将调度名称为“ valueChanged”的事件。 发出的数据将存储在事件的detail属性中。 如果提供别名,则使用该值。 例如, @Output('myClick') clicks = new EventEmitter<string& gt;(); 导致名称为“ myClick”的调度事件。

5.更新NgModule (5. Update NgModule)

Following are the major steps that need to be followed in app.module.ts:

以下是app.module.ts中需要遵循的主要步骤:

  1. Remove the default bootstrap array which is set to AppComponent

    删除设置为AppComponent的默认bootstrap数组

  2. Since our ButtonComponent is not a part of any other component, and is also not a root of an Angular application, we need to tell Angular to compile it specifically. For this we put it on the entryComponents list. Otherwise Angular tree shaking will drop this component from the prod bundle.

    由于我们的ButtonComponent不是任何其他组件的一部分,也不是Angular应用程序的根,因此我们需要告诉Angular专门对其进行编译。 为此,我们将其放在entryComponents列表中。 否则,角度树摇晃会使该组件从产品束中掉落。

  3. Add ngDoBootstrap() to tell Angular to use this module for bootstrapping.

    添加ngDoBootstrap()告诉Angular使用该模块进行引导。

  4. Angular provides the createCustomElement() function for converting an Angular component, together with its dependencies, to a custom element. The createCustomElement() function is expecting to get two parameter:

    Angular提供了createCustomElement ()函数,用于将Angular组件及其依赖项转换为自定义元素。 createCustomElement()函数期望获得两个参数:

  • First, the Angular component which should be used to create the element.

    首先,应使用Angular组件创建元素。
  • Second, a configuration object. This object needs to include the injector property which is set to the current Injector instance.

    第二,配置对象。 该对象需要包括设置为当前Injector实例的注射器属性。

5. The next step is to register the newly created custom element in the browser. This is done by calling customElements.define(). Please note that this is not Angular. The customElements read-only property belongs to the Window interface. It returns a reference to the CustomElementRegistry object. This object can be used to register new custom elements. It can also get information about previously registered custom elements in the browser.

5.下一步是在浏览器中注册新创建的自定义元素。 这是通过调用customElements.define() 。 请注意,这不是Angular。 customElements只读属性属于Window接口。 它返回对CustomElementRegistry对象的引用。 该对象可用于注册新的自定义元素。 它还可以获取有关浏览器中先前注册的自定义元素的信息。

The customElements.define() method needs two parameter:

customElements.define()方法需要两个参数:

  • The first parameter is of type string and contains the name of the element. Passing the string ‘app-button’ means that the custom element <app-button> will be registered and can be used in the HTML code.

    第一个参数的类型为字符串,并包含元素的名称。 传递字符串' app-button'意味着自定义元素<app-butt on>将被注册并可以在HTML代码中使用。

  • The second parameter is the custom element which has been created before.

    第二个参数是之前创建的自定义元素。

6. Now replace target value in tsconfig.json from es5 to es2015 as in browsers that support Custom Elements natively, the specification requires developers to use ES2015 classes to define Custom Elements.

6.现在替换target在值tsconfig.jsones5es2015在浏览器的支持自定义元素本身,规范要求开发者使用ES2015类来定义自定义元素。

6.构建并运行 (6. Build and run)

In order to build we will use a standard ng build command. But since it outputs four files (runtime.js , scripts.js, polyfills.js and main.js) and we’d like to distribute our component as a single js file, we need to turn hashing file names off. Let’s modify the scripts in package.json and add package entry:

为了构建,我们将使用标准的ng build命令。 但由于它输出四个文件( runtime.jsscripts.jspolyfills.jsmain.js ),我们希望我们的分发组件作为一个单一的js文件,我们需要把散列文件名了。 让我们修改package.jsonscripts并添加package条目:

"scripts": {…,"build": "ng build --prod --output-hashing=none",// For Windows:
"package": "jscat ./dist/angular-custom-elements/runtime.js ./dist/angular-custom-elements/polyfills.js ./dist/angular-custom-elements/scripts.js ./dist/angular-custom-elements/main.js > custom-button-element.js",// For Mac or Linux:
"package": "cat ./dist/angular-custom-elements/runtime.js ./dist/angular-custom-elements/polyfills.js ./dist/angular-custom-elements/scripts.js ./dist/angular-custom-elements/main.js > custom-button-element.js",…,}

Since Windows OS has no cat command run npm i jscat.

由于Windows操作系统没有cat命令,请运行npm i jscat

Save all and finally run:

保存所有并最终运行:

npm run build && npm run package

The command generates custom-button-element.js that you can include in <script> of an HTML page to see our custom element working.

该命令会生成custom-button-element.js ,您可以将其包含在HTML页面的<script> ,以查看我们的自定义元素是否有效。

Here is an example:

这是一个例子:

摘要 (Summary)

In summary we’ve:

总而言之,我们已经:

  • Added important libraries for implementation

    添加了重要的实现库
  • Registered the component in browser’s CustomElementRegistry

    在浏览器的CustomElementRegistry中注册了组件
  • Combined the build artifacts to a single file

    将构建工件组合到单个文件中

Complete source code can be found here.

完整的源代码可以在这里找到。

Did you learn something new? If so please clap ? button below️ so more people can see this.

你学到新东西了吗? 如果是这样,请拍手? 下方的按钮 ️,以便更多人可以看到。

翻译自: https://www.freecodecamp.org/news/how-to-create-angular-6-custom-elements-web-components-c88814dc6e0a/

angular 自定义组件

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/7507.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息