HTML中的自定义标签6,Angular6 用户自定义标签开发的实现方法

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。

dabfc976dbe63843d21ff637aaae0e4b.png

增加标签功能

修改app.component.html 内容

  • {{item}}

为对应的类增加 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应用,通过增加按钮,要以向列表中增加元素。

e23e9534cbcdf7096d78cfdff31eaa18.png

应用状态

将完成内容转换为自定义标签

增加@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页面

CustomTag

页面重新出现在浏览器中了,功能也同先前一模一样。

由于浏览器版本的原因可能会出现下面错误,无法创建自定义标签

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 = new EventEmitter();

addItem(item:string){

console.log(`${item} to be added!`);

this.items.push(item);

// 向外发送自定义事件

this.itemAdded.emit(item);

}

items:string[] =[];

}

在客户端页面可以通过自定义标签对象的addEventListener()方法增加自定义事件响应,通过 event.detail可以获取到angular内部发送的内容

var items = document.querySelector('custom-items');

items.addEventListener('itemAdded', (event) => {

console.log(event);

})

完结与发布

在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文件中采用如下方式引用了定义标签的输出,如果其他用户使用会非常不便,

我们可以通过使用cat命令将这些文件按照上面顺序合并成一个文件

$cat runtime.js polyfills.js scripts.js main.js > custom-items.js

这样用户就可以引用单个文件来使用我们制做的custom-items了。

一定注记合并文件的次序,需要严格按照上述次序进行,否则脚本可能不能正常工作。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值