1. 程式人生 > >angular custom Element 自定義web component

angular custom Element 自定義web component

als 強行 spa jquery app 我們 false 計算 大小

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/[email protected]/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