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新建完相應(yīng)文件后會通過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>
為對應(yīng)的類增加 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應(yīng)用,通過增加按鈕,要以向列表中增加元素。

應(yīng)用狀態(tài)
將完成內(nèi)容轉(zhuǎn)換為自定義標簽
增加@angular/comonents信賴
$ng add @angular/elements
修改app.module.ts
從包中導(dǎo)入相關(guān)依賴:
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()方法增加自定義事件響應(yīng),通過 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)建,由于我們關(guān)閉了文件名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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- AngularJS實現(xiàn)標簽頁的兩種方式
- Angular.js中ng-include用法及多標簽頁面的實現(xiàn)方式詳解
- angular4模塊中給標簽添加背景圖的實現(xiàn)方法
- AngularJS標簽頁tab選項卡切換功能經(jīng)典實例詳解
- 詳解Angular.js數(shù)據(jù)綁定時自動轉(zhuǎn)義html標簽及內(nèi)容
- AngularJS 打開新的標簽頁實現(xiàn)代碼
- 詳解angular用$sce服務(wù)來過濾HTML標簽
- Angular中點擊li標簽實現(xiàn)更改顏色的核心代碼
- Angular 實現(xiàn)輸入框中顯示文章標簽的實例代碼
相關(guān)文章
angular inputNumber指令輸入框只能輸入數(shù)字的實現(xiàn)
這篇文章主要介紹了angular inputNumber指令輸入框只能輸入數(shù)字的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Angular 實現(xiàn)輸入框中顯示文章標簽的實例代碼
這篇文章主要介紹了Angular 實現(xiàn)輸入框中顯示文章標簽的實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11
AngularJS框架中的雙向數(shù)據(jù)綁定機制詳解【減少需要重復(fù)的開發(fā)代碼量】
這篇文章主要介紹了AngularJS框架中的雙向數(shù)據(jù)綁定機制,結(jié)合實例形式分析了AngularJS雙向數(shù)據(jù)綁定機制的原理及實現(xiàn)方法,以及減少需要重復(fù)開發(fā)代碼量的優(yōu)勢,需要的朋友可以參考下2017-01-01
AngularJS應(yīng)用開發(fā)思維之依賴注入3
這篇文章主要為大家詳細介紹了AngularJS應(yīng)用開發(fā)思維之依賴注入第三篇,感興趣的小伙伴們可以參考一下2016-08-08

