分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

angular custom Element 自定义web component

发布时间:2023-09-06 01:49责任编辑:郭大石关键词:暂无标签

angular 自定义web组件:

首先创建一个名为myCustom的组件。

引入app.module:

...import {customComponent} from ‘ ./myCustom.component‘;@NgModule({ ?declarations:[AppComponent,customComponent], ?entryComponents:[customComponent] ???....})export class AppModule{}

  

全局注册:

app.component:

import { Component,Injector} from ‘@angular/core‘;import { createCustomElement} from ‘@angular/elements‘;import {customComponents} from ‘./myCustom.component‘;@Component({})export class AppComponent{ constructor(private injector:Injector){ ??const customElementRef=createCustomElement(createCustomElement,{injector}); ??customElements.define(‘my-test‘,customElementRef); ?????}}

Ok,这样完成了‘my-test‘的全局,接下来可以像是用web component那样使用它了.

进入我们的主html:

Index.html

<html><body> ?<app-root></app-root> ?<!-- 这是angular程序主引导接口 --> ?<my-test></my-test> ???<!-- 全局注册的angular组件可以直接放在html里使用--></body></html>

注意:

1. 放在app-root前面,效果是一样的。没有先后之分。

2. my-test的注入依赖,继承自app.component。你可以放心地在里面使用。

3. 作为web component 时,input不能接受变量。output不生效。。

问:

既然angular可以注册全局web component ,那么是否能结合react使用?

 当然可以,接着上面的列子:

<html><body> ?<app-root></app-root> ?<!-- 这是angular程序主引导接口 --> ?<my-test></my-test> ???<!-- 全局注册的angular组件可以直接放在html里使用--> <div id=‘react-app‘></div></body> ?<!-- 引入react.js --> ???<script src="https://unpkg.com/react@16/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script><script type=‘text/babel‘> class ReactApp extends React.Component{ ?state={ ???showAngularComponent:false ?} ??render(){ ????const state=this.state; ????return ( ?????<div> ???????{state.showAngularComponent?<my-test></my-test>:null} ????????<button onClick={()=>this.setState({showAngularComponent:!state.showAngularComponent})}>toggle</button> ????????</div> ????) ????} } ReactDOM.render(<ReactApp/>,document.getElementById(‘react-app‘))</script></html> ???

  完美运行。

 angular component 注册为web component 的技术。让angular的灵活性瞬间暴涨!但是那么有必要结合react使用吗?

当然是得依你的业务要求来定了,比如你的领导强行指定你使用react。

但是当你面对一些功能复杂的组件或页面开发时,react的相对低下的效率,以及大面积重复计算、缓慢的性能,可能让你非常苦恼。此时或许你能考虑下用angular便捷迅速地为你的react项目提供一个高性能且稳定的组件。

加上ng6再一次减肥,核心库如同jquery一样的大小,angular的未来,一片光明。

---

使用custom element之前:

安装webcomponents填充库:

  npm install webcomponents/webcomponentsjs --save;

polyfill.ts中引入:

import ‘@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js‘

angular custom Element 自定义web component

原文地址:https://www.cnblogs.com/ztwBlog/p/8847531.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved