首頁  >  文章  >  web前端  >  Angular Component使用案例詳解

Angular Component使用案例詳解

php中世界最好的语言
php中世界最好的语言原創
2018-05-03 15:09:451843瀏覽

這次帶給大家Angular Component使用案例詳解,Angular Component使用的注意事項有哪些,以下就是實戰案例,一起來看一下。

Web Component

在介紹Angular Component之前,我們先簡單了解下W3C Web Components

定義

W3C為統一元件化標準方式,提出Web Component的標準。

每個元件包含自己的html、css、js程式碼。
Web Component標準包含以下四個重要的概念:
1.Custom Elements(自訂標籤):可以建立自訂HTML 標記和元素;
2.HTML Templates(HTML模版):使用< ;template> 標籤去預先定義一些內容,但不會載入到頁面,而是使用JS 程式碼去初始化它;
3.Shadow DOM(虛擬DOM):可以建立完全獨立與其他元素的DOM子樹;
4.HTML Imports(HTML導入):一種在HTML 文件中引入其他HTML 文件的方法,

概括來說就是,可以建立自訂標籤來引入元件是前端元件化的基礎,在頁面引用HTML 檔案和HTML 範本是用來支撐編寫元件檢視和元件資源管理,而Shadow DOM 則是隔離組件間程式碼的衝突和影響。

範例

定義hello-component

<template id="hello-template">
  <style>
    h1 {
      color: red;
    }
  </style>
  <h1>Hello Web Component!</h1>
</template>
<script>
  // 指向导入文档,即本例的index.html
  var indexDoc = document;
  // 指向被导入文档,即当前文档hello.html
  var helloDoc = (indexDoc._currentScript || indexDoc.currentScript).ownerDocument;
  // 获得上面的模板
  var tmpl = helloDoc.querySelector('#hello-template');
  // 创建一个新元素的原型,继承自HTMLElement
  var HelloProto = Object.create(HTMLElement.prototype);
  // 设置 Shadow DOM 并将模板的内容克隆进去
  HelloProto.createdCallback = function() {
    var root = this.createShadowRoot();
    root.appendChild(indexDoc.importNode(tmpl.content, true));
  };
  // 注册新元素
  var hello = indexDoc.registerElement('hello-component', {
    prototype: HelloProto
  });
</script>

使用hello-component

<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="author" content="赖祥燃, laixiangran@163.com, http://www.laixiangran.cn"/>
  <title>Web Component</title>
  <!--导入自定义组件-->
  <link rel="import" href="hello.html" rel="external nofollow" >
</head>
<body>
  <!--自定义标签-->
  <hello-component></hello-component>
</body>
</html>

從以上程式碼可看到,hello. html 為標準定義的元件(名稱為hello-component ),在這個元件中有自己的結構、樣式及邏輯,然後在index.html 中引入該元件文件,即可像一般標籤一樣使用。

Angular Component

Angular Component屬於指令的一種,可以理解為擁有模板的指令。其它兩種是屬性型指令和結構型指令。

基本組成

@Component({
  selector: 'demo-component',
  template: 'Demo Component'
})
export class DemoComponent {}
  1. 元件裝飾器:每個元件類別必須用@component裝飾才能成為Angular元件。

  2. 元件元資料:元件元資料:selector、template等,下文將著重講解每個元資料的意義。

  3. 元件類:元件其實也是一個普通的類,元件的邏輯都在元件類別裡定義並實作。

  4. 元件模板:每個元件都會關聯一個模板,這個模板最終會渲染到頁面上,頁面上這個DOM元素就是此元件實例的宿主元素。

元件元資料

自身元資料屬性

##類型作用animationsAnimationEntryMetadata[]#設定元件的動畫##changeDetectionencapsulationentryComponentsinterpolationmoduleIdstyleUrlsstylestemplatetemplateUrl
#名稱
ChangeDetectionStrategy 設定元件的變化監控策略
#ViewEncapsulation 設定元件的視圖包裝選項
#any[] #設定將會動態插入到該元件檢視中的元件清單
[string, string] #自訂元件的內插標記,預設為雙大括號
string 設定該元件在ES/CommonJS 規範下的模組id,它被用來解析模板樣式的相對路徑
string[] 設定元件所引用的外部樣式檔案
string[] 設定元件所使用的內嵌樣式
string 設定元件的內嵌範本
string######設定元件模板所在路徑#############viewProviders######Provider[]#####################################################設定元件及其所有子元件(不含ContentChildren)可用的服務#############

從core/Directive 繼承

##host{[key: string]: string}設定元件的事件、動作和屬性等inputsstring[] 設定元件的輸入屬性outputs#string[]#設定元件的輸出屬性providersProvider[]設定元件及其所有子元件(含ContentChildren)可用的服務(queries{[key: string]: any}#設定需要被注入到元件的查詢 selectorstring設定用於在範本中識別該元件的

几种元数据详解

以下几种元数据的等价写法会比元数据设置更简洁易懂,所以一般推荐的是等价写法。

inputs

@Component({
  selector: 'demo-component',
  inputs: ['param']
})
export class DemoComponent {
  param: any;
}

等价于:

@Component({
  selector: 'demo-component'
})
export class DemoComponent {
  @Input() param: any;
}

outputs

@Component({
  selector: 'demo-component',
  outputs: ['ready']
})
export class DemoComponent {
  ready = new eventEmitter<false>();
}

等价于:

@Component({
  selector: 'demo-component'
})
export class DemoComponent {
  @Output() ready = new eventEmitter<false>();
}

host

@Component({
  selector: 'demo-component',
  host: {
    '(click)': 'onClick($event.target)', // 事件
    'role': 'nav', // 属性
    '[class.pressed]': 'isPressed', // 类
  }
})
export class DemoComponent {
  isPressed: boolean = true;
  onClick(elem: HTMLElement) {
    console.log(elem);
  }
}

等价于:

@Component({
  selector: 'demo-component'
})
export class DemoComponent {
  @HostBinding('attr.role') role = 'nav';
  @HostBinding('class.pressed') isPressed: boolean = true;
 
  @HostListener('click', ['$event.target'])
  onClick(elem: HTMLElement) {
    console.log(elem);
  }
}

queries - 视图查询

@Component({
  selector: 'demo-component',
  template: `
    <input #theInput type=&#39;text&#39; />
    <p>Demo Component</p>
  `,
  queries: {
    theInput: new ViewChild('theInput')
  }
})
export class DemoComponent {
  theInput: ElementRef;
}

等价于:

@Component({
  selector: 'demo-component',
  template: `
    <input #theInput type=&#39;text&#39; />
    <p>Demo Component</p>
  `
})
export class DemoComponent {
  @ViewChild('theInput') theInput: ElementRef;
}

queries - 内容查询

<my-list>
  <li *ngFor="let item of items;">{{item}}</li>
</my-list>
@Directive({
  selector: 'li'
})
export class ListItem {}
@Component({
  selector: 'my-list',
  template: `
    <ul>
      <ng-content></ng-content>
    </ul>
  `,
  queries: {
    items: new ContentChild(ListItem)
  }
})
export class MyListComponent {
  items: QueryList<ListItem>;
}

等价于:

@Component({
  selector: 'my-list',
  template: `
    <ul>
      <ng-content></ng-content>
    </ul>
  `
})
export class MyListComponent {
  @ContentChild(ListItem) items: QueryList<ListItem>;
}

styleUrls、styles

styleUrls和styles允许同时指定。

优先级:模板内联样式 > styleUrls > styles。

建议:使用styleUrls引用外部样式表文件,这样代码结构相比styles更清晰、更易于管理。同理,模板推荐使用templateUrl引用模板文件。

changeDetection

ChangeDetectionStrategy.Default:组件的每次变化监测都会检查其内部的所有数据(引用对象也会深度遍历),以此得到前后的数据变化。

ChangeDetectionStrategy.OnPush:组件的变化监测只检查输入属性(即@Input修饰的变量)的值是否发生变化,当这个值为引用类型(Object,Array等)时,则只对比该值的引用。

显然,OnPush策略相比Default降低了变化监测的复杂度,很好地提升了变化监测的性能。如果组件的更新只依赖输入属性的值,那么在该组件上使用OnPush策略是一个很好的选择。

encapsulation

ViewEncapsulation.None:无 Shadow DOM,并且也无样式包装。

ViewEncapsulation.Emulated:无 Shadow DOM,但是通过Angular提供的样式包装机制来模拟组件的独立性,使得组件的样式不受外部影响,这是Angular的默认设置。

ViewEncapsulation.Native:使用原生的 Shadow DOM 特性。

生命周期

当Angular使用构造函数新建组件后,就会按下面的顺序在特定时刻调用这些生命周期钩子方法:

名稱 #型別 作用
exportAs string 設定元件實例在範本中的別名,使得可以在範本中呼叫
依賴注入
css選擇器(元件的自訂標籤)
生命周期钩子 调用时机
ngOnChanges 在ngOnInit之前调用,或者当组件输入数据(通过@Input装饰器显式指定的那些变量)变化时调用。
ngOnInit 第一次ngOnChanges之后调用。建议此时获取数据,不要在构造函数中获取。
ngDoCheck 每次变化监测发生时被调用。
ngAfterContentInit 使用
ngAfterContentChecked ngAfterContentInit后被调用,或者每次变化监测发生时被调用(只适用组件)。
ngAfterViewInit 创建了组件的视图及其子视图之后被调用(只适用组件)。
ngAfterViewChecked ngAfterViewInit,或者每次子组件变化监测时被调用(只适用组件)。
ngOnDestroy 销毁指令/组件之前触发。此时应将不会被垃圾回收器自动回收的资源(比如已订阅的观察者事件、绑定过的DOM事件、通过setTimeout或setInterval设置过的计时器等等)手动销毁掉。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue里调用百度地图步骤详解

vue中如何使用jointjs属性

以上是Angular Component使用案例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn