

可以通过修改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了。
一定注记合并文件的次序,需要严格按照上述次序进行,否则脚本可能不能正常工作。
示例代码
在线示例
