可以通過修改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了。
一定注記合并文件的次序,需要嚴格按照上述次序進行,否則腳本可能不能正常工作。
示例代碼
在線示例
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com