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'

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM