2018年4月23隨著angular6 發布,我們可以看到在其官方手冊中的模板元素章節中增加了一個Element 條目(中文),通過說明我們可以知道這個功能可以幫助我們將angular以html標簽的形式嵌入到非angular的頁面環境中。下面我們就通過一個簡單的例子演示Angular6中的這一新功能。
新建angular工程
通過ng命令新建custom-tag工程
ng new custom-tag
cli新建完相應文件后會通過npm下載所信賴的包,完成后進入目錄驗證工作空間是否正常。
$cd custom-tag$ng serve --open
--open參數的作用是直接打開瀏覽器,也可以通過瀏覽器中直接輸入localhost:4200。
增加標簽功能
修改app.component.html 內容
<!--The content below is only a placeholder and can be replaced.--><!--<div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg=="></div><h2>Here are some links to help you start: </h2><ul> <li> <h2><a target="_blank" rel="noopener" rel="external nofollow" >Tour of Heroes</a></h2> </li> <li> <h2><a target="_blank" rel="noopener" rel="external nofollow" >CLI Documentation</a></h2> </li> <li> <h2><a target="_blank" rel="noopener" rel="external nofollow" >Angular blog</a></h2> </li></ul>--><input #inputtext type="text" placeholder="條目"><input type="button" value="增加" (click)="addItem(inputtext.value)"><ul> <li *ngFor="let item of items">{{item}}</li></ul>
為對應的類增加 addItem()方法,向類中的條目集合(items)增加用戶輸入的一個條目。
import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { addItem(item:string){ console.log(`${item} to be added!`); this.items.push(item); } items:string[] =[];}
小結
到目前為止這是一個普通的angular應用,通過增加按鈕,要以向列表中增加元素。
應用狀態
將完成內容轉換為自定義標簽
增加@angular/comonents信賴
$ng add @angular/elements
修改app.module.ts
從包中導入相關依賴:
import { Injector} from '@angular/core';import { createCustomElement } from '@angular/elements';
將AppComponent改為動態組件,并通過createCustomElement()注冊AppComponent為custom-items
import { BrowserModule } from '@angular/platform-browser';import { NgModule,Injector } from '@angular/core';import { createCustomElement } from '@angular/elements';import { AppComponent } from './app.component';@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], //bootstrap: [AppComponent] entryComponents : [ AppComponent ]})export class AppModule { constructor(private injector : Injector){ const cust_tag = createCustomElement(AppComponent, {injector : this.injector}); customElements.define('custom-items',cust_tag); } ngDoBootstrap() {} }
修改index.html頁面
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>CustomTag</title> <base href="/" rel="external nofollow" > <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico" rel="external nofollow" ></head><body> <!--<app-root></app-root>--> <custom-items></custom-items></body></html>
頁面重新出現在瀏覽器中了,功能也同先前一模一樣。
由于瀏覽器版本的原因可能會出現下面錯誤,無法創建自定義標簽
elements.js:384 Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
at NgElementImpl.NgElement [as constructor] (elements.js:384)
at new NgElementImpl (elements.js:420)
at new AppModule (app.module.ts:24)
at _createClass (core.js:8421)
at _createProviderInstance (core.js:8393)
at initNgModule (core.js:8326)
at new NgModuleRef_ (core.js:9052)
at createNgModuleRef (core.js:9041)
at Object.debugCreateNgModuleRef [as createNgModuleRef] (core.js:10866)
at NgModuleFactory_.push../node_modules/@angular/core/fesm5/core.js.NgModuleFactory_.create (core.js:11583)
可以通過修改tsconfig.json中的構建目標至es6解決該問題
{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es6", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] }}
增加外部事件
通過output 可以為自定義標簽增加自定義事件
import { Component,Output, EventEmitter } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { @Output() itemAdded:EventEmitter<string> = new EventEmitter<string>(); addItem(item:string){ console.log(`${item} to be added!`); this.items.push(item); // 向外發送自定義事件 this.itemAdded.emit(item); } items:string[] =[];}
在客戶端頁面可以通過自定義標簽對象的addEventListener()方法增加自定義事件響應,通過 event.detail可以獲取到angular內部發送的內容
<script> var items = document.querySelector('custom-items'); items.addEventListener('itemAdded', (event) => { console.log(event); }) </script>
完結與發布
在package.json中增加發布腳本
"scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod --output-hashing none", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" },
通過npm run build 執行構建,由于我們關閉了文件名hash,得到的輸出目錄內容如下:
liunan@liunan-desktop:~/webDev/custom-tag$ ls ./dist/custom-tag/3rdpartylicenses.txt favicon.ico index.html main.js polyfills.js runtime.js scripts.js styles.css
我們可以看到輸出的index.html文件中采用如下方式引用了定義標簽的輸出,如果其他用戶使用會非常不便,
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="scripts.js"></script><script type="text/javascript" src="main.js"></script>
我們可以通過使用cat命令將這些文件按照上面順序合并成一個文件
$cat runtime.js polyfills.js scripts.js main.js > custom-items.js
這樣用戶就可以引用單個文件來使用我們制做的custom-items了。
一定注記合并文件的次序,需要嚴格按照上述次序進行,否則腳本可能不能正常工作。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答