Angular6 用戶自定義標簽開發(fā)的實現(xiàn)方法
2018年4月23隨著angular6 發(fā)布,我們可以看到在其官方手冊中的模板元素章節(jié)中增加了一個Element 條目(中文),通過說明我們可以知道這個功能可以幫助我們將angular以html標簽的形式嵌入到非angular的頁面環(huán)境中。下面我們就通過一個簡單的例子演示Angular6中的這一新功能。
新建angular工程
通過ng命令新建custom-tag工程
ng new custom-tag
cli新建完相應文件后會通過npm下載所信賴的包,完成后進入目錄驗證工作空間是否正常。
$cd custom-tag $ng serve --open
--open參數(shù)的作用是直接打開瀏覽器,也可以通過瀏覽器中直接輸入localhost:4200。

增加標簽功能
修改app.component.html 內(nèi)容
<!--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[] =[];
}
小結(jié)
到目前為止這是一個普通的angular應用,通過增加按鈕,要以向列表中增加元素。

應用狀態(tài)
將完成內(nèi)容轉(zhuǎn)換為自定義標簽
增加@angular/comonents信賴
$ng add @angular/elements
修改app.module.ts
從包中導入相關依賴:
import { Injector} from '@angular/core';
import { createCustomElement } from '@angular/elements';
將AppComponent改為動態(tài)組件,并通過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>
頁面重新出現(xiàn)在瀏覽器中了,功能也同先前一模一樣。
由于瀏覽器版本的原因可能會出現(xiàn)下面錯誤,無法創(chuàng)建自定義標簽
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中的構(gòu)建目標至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);
// 向外發(fā)送自定義事件
this.itemAdded.emit(item);
}
items:string[] =[];
}
在客戶端頁面可以通過自定義標簽對象的addEventListener()方法增加自定義事件響應,通過 event.detail可以獲取到angular內(nèi)部發(fā)送的內(nèi)容
<script>
var items = document.querySelector('custom-items');
items.addEventListener('itemAdded', (event) => {
console.log(event);
})
</script>
完結(jié)與發(fā)布
在package.json中增加發(fā)布腳本
"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 執(zhí)行構(gòu)建,由于我們關閉了文件名hash,得到的輸出目錄內(nèi)容如下:
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了。
一定注記合并文件的次序,需要嚴格按照上述次序進行,否則腳本可能不能正常工作。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
AngularJS使用ng-Cloak阻止初始化閃爍問題的方法
這篇文章主要介紹了AngularJS使用ng-Cloak阻止初始化閃爍問題的方法,結(jié)合實例形式分析了AngularJS使用ng-Cloak來解決初始化時出現(xiàn)閃爍問題的相關技巧,需要的朋友可以參考下2016-11-11
詳解webpack+es6+angular1.x項目構(gòu)建
這篇文章主要介紹了詳解webpack+es6+angular1.x項目構(gòu)建, 小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
簡介AngularJS中使用factory和service的方法
這篇文章主要簡單介紹了AngularJS中使用factory和service的方法,主要針對自定義工廠和服務的創(chuàng)建來講,需要的朋友可以參考下2015-06-06
詳解angularJS動態(tài)生成的頁面中ng-click無效解決辦法
這篇文章主要介紹了詳解angularJS動態(tài)生成的頁面中ng-click無效解決辦法,非常具有實用價值,需要的朋友可以參考下2017-06-06
在AngularJS框架中處理數(shù)據(jù)建模的方式解析
這篇文章主要介紹了在AngularJS框架中處理數(shù)據(jù)建模的方式,作者同時也對AngularJS使用過程中的一些"坑"作了介紹,需要的朋友可以參考下2016-03-03
Angular 中使用 FineReport不顯示報表直接打印預覽
這篇文章主要介紹了Angular 中使用 FineReport不顯示報表直接打印預覽,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08

