亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Angular6 用戶自定義標(biāo)簽開發(fā)的實(shí)現(xiàn)方法

 更新時(shí)間:2019年01月08日 09:33:59   作者:清洼  
這篇文章主要介紹了Angular6 用戶自定義標(biāo)簽開發(fā)的實(shí)現(xiàn)方法,下面我們就通過一個(gè)簡(jiǎn)單的例子演示Angular6中的這一新功能,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,需要的朋友可以參考下

2018年4月23隨著angular6 發(fā)布,我們可以看到在其官方手冊(cè)中的模板元素章節(jié)中增加了一個(gè)Element 條目(中文),通過說明我們可以知道這個(gè)功能可以幫助我們將angular以html標(biāo)簽的形式嵌入到非angular的頁面環(huán)境中。下面我們就通過一個(gè)簡(jiǎn)單的例子演示Angular6中的這一新功能。

新建angular工程

通過ng命令新建custom-tag工程

ng new custom-tag

cli新建完相應(yīng)文件后會(huì)通過npm下載所信賴的包,完成后進(jìn)入目錄驗(yàn)證工作空間是否正常。

$cd custom-tag
$ng serve --open

--open參數(shù)的作用是直接打開瀏覽器,也可以通過瀏覽器中直接輸入localhost:4200。

增加標(biāo)簽功能

修改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>

為對(duì)應(yīng)的類增加 addItem()方法,向類中的條目集合(items)增加用戶輸入的一個(gè)條目。

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é)

到目前為止這是一個(gè)普通的angular應(yīng)用,通過增加按鈕,要以向列表中增加元素。

應(yīng)用狀態(tài)

將完成內(nèi)容轉(zhuǎn)換為自定義標(biāo)簽

增加@angular/comonents信賴

$ng add @angular/elements

修改app.module.ts

從包中導(dǎo)入相關(guān)依賴:

import { Injector} from '@angular/core';
import { createCustomElement } from '@angular/elements';

將AppComponent改為動(dòng)態(tài)組件,并通過createCustomElement()注冊(cè)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)在瀏覽器中了,功能也同先前一模一樣。

由于瀏覽器版本的原因可能會(huì)出現(xiàn)下面錯(cuò)誤,無法創(chuàng)建自定義標(biāo)簽

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)建目標(biāo)至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 可以為自定義標(biāo)簽增加自定義事件

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[] =[];
}

在客戶端頁面可以通過自定義標(biāo)簽對(duì)象的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文件中采用如下方式引用了定義標(biāo)簽的輸出,如果其他用戶使用會(huì)非常不便,

<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命令將這些文件按照上面順序合并成一個(gè)文件

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

這樣用戶就可以引用單個(gè)文件來使用我們制做的custom-items了。

一定注記合并文件的次序,需要嚴(yán)格按照上述次序進(jìn)行,否則腳本可能不能正常工作。

示例代碼

在線示例

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論