angular custom Element 自定义web component

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'

 

 

 

 

 

posted @ 2018-04-15 14:31  Jnew  阅读(1531)  评论(0编辑  收藏  举报