首頁  >  文章  >  web前端  >  深入了解angular中的@Component裝飾器

深入了解angular中的@Component裝飾器

青灯夜游
青灯夜游轉載
2022-05-27 20:13:243038瀏覽

Component是Directive的子類,它是一個裝飾器,用來標記某個類別為Angular元件。以下這篇文章就來帶大家深入了解angular中的@Component裝飾器,希望對大家有幫助。

深入了解angular中的@Component裝飾器

一、@Component 裝飾器

1.1 <span style="font-size: 18px;">@Component</span> 裝飾器的用途

聲明一個元件時,在元件類別的之上要用@Component裝飾器來告知Angular這是一個元件。 【相關教學推薦:《angular教學》】

import { Component, OnInit } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-product-alerts&#39;,
  templateUrl: &#39;./product-alerts.component.html&#39;,
  styleUrls: [&#39;./product-alerts.component.css&#39;]
})
export class ProductAlertsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

#1.2 <span style="font-size: 18px;">@Component</span>

裝飾器的常用選項 裝飾器繼承於 ,這個css選擇器用於在模板中標記出該指令,並觸發該指令的實例化。 繼承自@Directive裝飾器的選項選項selectorinputs· directiveProperty 用來指定要寫入值的指令內屬性。 · directiveProperty 指定要發出事件的元件屬性。 · bindingProperty 指定要附加事件處理器的 HTML 屬性。 #服務提供者的集合
@ComponentDirective
1.2.1

類型 說明

#string css選擇器名,用於在模板中標記出該指令(元件),並觸發其實例化
string[] Angular 會在變更偵測期間自動更新輸入屬性。 inputs 屬性定義了一組從 directiveProperty 指向 bindingProperty 的配置項:· bindingProperty 用來指定要從中讀取值的 DOM 屬性。當沒有提供 bindingProperty 時,就假設它和 directiveProperty 一樣。
outputs string[] #一組可供事件綁定的輸出屬性。當輸出屬性發出事件時,就會呼叫範本中一個附加到該事件的處理器。每個輸出屬性都會把 directiveProperty 對應到 bindingProperty:
provides Provider[]
exportAs string

一個或多個名字,可以用來在模板中把該指令賦值給一個變數。當有多個名字時,請使用逗號分隔它們。
queries######{[key:string]:any}######設定將要注入到該指令中的一些查詢。內容查詢會在呼叫 ngAfterContentInit 回呼之前設定好。試著查詢會在呼叫 ngAfterViewInit 回呼之前設定好。 ############jit######true######如果為true,則該指令/元件將會被AOT 編譯器忽略,因此永遠只會被JIT 編譯。這個選項是為了支援未來的 Ivy 編譯器,目前還沒有效果。 ############host######{[key:string]:string}######使用一組鍵-值對,把類別的屬性對應到宿主元素的綁定(Property、Attribute 和事件)。 Angular 在變更偵測期間會自動檢查宿主 Property 綁定。如果綁定的值發生了變化,Angular 就會更新該指令的宿主元素。當 key 是宿主元素的 Property 時,這個 Property 值就會傳播到指定的 DOM 屬性。當 key 是 DOM 中的靜態 Attribute 時,這個 Attribute 值就會傳到宿主元素上指定的 Property 去。對於事件處理:###· 它的 key 就是該指令想要監聽的 DOM 事件。若要監聽全域事件,請把要監聽的目標加到事件名稱的前面。這個目標可以是 window、document 或 body。 ###· 它的 value 就是當該事件發生時要執行的語句。如果該語句傳回 false,那麼就會呼叫這個 DOM 事件的 preventDefault 函數。這個語句中可以引用局部變數 $event 來取得事件資料。 ############

1.2.2 @Component自己特有的選項

##preserveWhitespacesboolean為true 則保留,為false 則從編譯後的範本中移除可能多餘的空白字元。空白字元就是指那些能在 JavaScript 正規表示式中符合 \s 的字元。預設為 false,除非透過編譯器選項改寫了它。

二、 selector 选择器

可使用下列形式之一:

  • element-name: 根据元素名选取
  • [attribute]: 根据属性名选取
  • .class: 根据类名选取
  • [attribute=value]: 根据属性名和属性值选取
  • not(sub_selector): 只有当元素不匹配子选择器 sub_selector 的时候才选取
  • selector1, selector2: 无论 selector1 还是 selector2 匹配时都选取

2.1 <span style="font-size: 18px;">element-name</span>: 根据元素名选取

@Component({
    selector: &#39;app-element&#39;,
    template:  &#39;./element.component.html&#39;,
    styleUrls: [&#39;./element.component.css&#39;]
})
<app-element></app-element>

2.2 <span style="font-size: 18px;">[attribute]</span>: 根据属性名选取

@Component({
    selector: &#39;[app-element]&#39;,
    template:  &#39;./element.component.html&#39;,
    styleUrls: [&#39;./element.component.css&#39;]
})
<div app-element></div>

2.3 <span style="font-size: 18px;">.class</span>: 根据类名选取

@Component({
    selector: &#39;.app-element&#39;,
    template:  &#39;./element.component.html&#39;,
    styleUrls: [&#39;./element.component.css&#39;]
})
<div class="app-element"></div>

三、 host: {[key:string]:string}

使用一组键-值对,把类的属性映射到宿主元素的绑定(Property、Attribute 和事件)。
Angular 在变更检测期间会自动检查宿主 Property 绑定。 如果绑定的值发生了变化,Angular 就会更新该指令的宿主元素。

  • 当 key 是宿主元素的 Property 时,这个 Property 值就会传播到指定的 DOM 属性。
  • 当 key 是 DOM 中的静态 Attribute 时,这个 Attribute 值就会传播到宿主元素上指定的 Property 去。
  • 注意属性的值默认为变量,如果直接使用属性值,需要加字符串单引号或者双引号,变量直接在组件里定义即可

对于事件处理:

  • 它的 key 就是该指令想要监听的 DOM 事件。 要想监听全局事件,请把要监听的目标添加到事件名的前面。 这个目标可以是 window、document 或 body。
  • 它的 value 就是当该事件发生时要执行的语句。如果该语句返回 false,那么就会调用这个 DOM 事件的 preventDefault 函数。 这个语句中可以引用局部变量 $event 来获取事件数据。

3.1 <span style="font-size: 18px;">attribute</span><span style="font-size: 18px;">property</span>

  • property:dom元素作为对象附加的内容,例如childNodes、firstChild等
  • attribute:HTML标签特性是dom节点自带的属性

异同:

  • 部分属性既属于 property ,又属于 attribute ,比如 id
  • attribute 初始化后不会再改变; property 默认值为初始值,会随着 dom 更新

所以在 angular2 中双向绑定实现是由 dom 的 property 实现的,所以指令绑定的是 property ,但是在某些情况下 dom 不存在某个 property 比如 colspan,rowspan 等,这时想要绑定 html 标签特性需要用到 attr:

<table width="100%" border="10px solid">
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td [attr.colspan]=colnum>January</td>
  </tr>
  <tr>
    <td [attr.colspan]=colnum>February</td>
  </tr>
</table>

let colnum:number = 2;

3.2 使用 <span style="font-size: 18px;">host</span> 绑定 <span style="font-size: 18px;">class</span>

@Component({
    selector: &#39;.app-element&#39;,
    template:  &#39;./element.component.html&#39;,
    styleUrls: [&#39;./element.component.css&#39;],
    host: {
        &#39;[class.default-class]&#39;: &#39;useDefault&#39;
    },
    encapsulation: ViewEncapsulation.None // 让宿主元素也用上 element.component.css 样式。否则,默认胶囊封装避免CSS污染。
})
export class AppElementComponent {
  @Input() useDefault = true;
}
<div class="app-element"></div>

3.3 使用 <span style="font-size: 18px;">host</span> 绑定 <span style="font-size: 18px;">style</span>

@Component({
    selector: &#39;.app-element&#39;,
    template:  &#39;./element.component.html&#39;,
    styleUrls: [&#39;./element.component.css&#39;],
    host: {
        &#39;[style.background]&#39;: &#39;inputBackground&#39;
    }
})
export class AppElementComponent {
  @Input() inputBackground = &#39;red&#39;;
}
<div class="app-element"></div>

3.4 使用 <span style="font-size: 18px;">host</span> 绑定事件

@Component({
    selector: &#39;.app-element&#39;,
    template:  &#39;./element.component.html&#39;,
    styleUrls: [&#39;./element.component.css&#39;],
    host: {
        &#39;(click)&#39;: &#39;onClick($event)&#39;
    }
})
export class AppElementComponent {
  public onClick($event) {
    console.log($event);
  }
}
<div class="app-element"></div>

四、 encapsulation(封装)

供模板和 CSS 样式使用的样式封装策略。

4.1 Web Components

通过一种标准化的非侵入的方式封装一个组件,每个组件能组织好它自身的 HTML 结构、CSS 样式、JavaScript 代码,并且不会干扰页面上的其他元素。

Web Components 由以下四种技术组成:

  • Custom Elements: 自定义元素HTML
  • Templates: HTML模板
  • Shadow DOM: 影子DOMHTML
  • Imports: HTML导入

4.2 Shadow DOM

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Shadow DOM</title>
    <style type="text/css">
        .shadowroot_son {
            color: #f00;
        }
    </style>
</head>
<body>
<p>我不在 Shadow Host内</p>
<div>Hello, world!</div>
<script>
 // 影子宿主(shadow host)
 var shadowHost = document.querySelector(&#39;.shadowhost&#39;);
 // 创建影子根(shadow root)
 var shadowRoot = shadowHost.createShadowRoot();
 // 影子根作为影子树的第一个节点,其他的节点比如p节点都是它的子节点。
 shadowRoot.innerHTML = &#39;<p>我在 Shadow Host内</p>&#39;;
</script>
</body>
<html>

4.3 <span style="font-size: 18px;">ViewEncapsulation</span>

ViewEncapsulation 允许设置三个可选的值:

  • ViewEncapsulation.Emulated: 无 Shadow DOM,但是通过 Angular 提供的样式包装机制来封装组件,使得组件的样式不受外部影响。这是 Angular 的默认设置。
  • ViewEncapsulation.ShadowDom: 使用原生的 Shadow DOM 特性
  • ViewEncapsulation.None: 无 Shadow DOM,并且也无样式包装

4.3.1 ViewEncapsulation.None

import { Component, ViewEncapsulation } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;my-app&#39;,
  template: `
    <h4>Welcome to Angular World</h4>
    <p class="greet">Hello {{name}}</p>
  `,
  styles: [`
    .greet {
      background: #369;
      color: white;
    }
  `],
  encapsulation: ViewEncapsulation.None // None | Emulated | ShadowDom
})
export class AppComponent {
  name: string = &#39;Semlinker&#39;;
}

ViewEncapsulation.None 设置的结果是没有 Shadow DOM,并且所有的样式都应用到整个 document,换句话说,组件的样式会受外界影响,可能被覆盖掉。

4.3.2 ViewEncapsulation.Emulated

import { Component, ViewEncapsulation } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;my-app&#39;,
  ...,
  encapsulation: ViewEncapsulation.Emulated // None | Emulated | ShadowDom
})
export class AppComponent {
  name: string = &#39;Semlinker&#39;;
}

ViewEncapsulation.Emulated 设置的结果是没有 Shadow DOM,但是通过 Angular 提供的样式包装机制来封装组件,使得组件的样式不受外部影响。虽然样式仍然是应用到整个 document,但 Angular 为 .greet 类创建了一个 [_ngcontent-cmy-0] 选择器。可以看出,我们为组件定义的样式,被 Angular 修改了。其中的 _nghost-cmy- 和 _ngcontent-cmy- 用来实现局部的样式

4.3.3 ViewEncapsulation.ShadowDom

import { Component, ViewEncapsulation } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;my-app&#39;,
  ...,
  encapsulation: ViewEncapsulation.ShadowDom // None | Emulated | ShadowDom
})
export class AppComponent {
  name: string = &#39;Semlinker&#39;;
}

ViewEncapsulation.ShadowDom 设置的结果是使用原生的 Shadow DOM 特性。Angular 会把组件按照浏览器支持的 Shadow DOM 形式渲染

更多编程相关知识,请访问:编程视频!!

#類型 說明
changeDetection #ChangeDetectionStrategy 當元件實例化之後,Angular 就會建立一個變更偵測器,它負責傳播組件各個綁定值的變化。此策略是下列數值之一:
· ChangeDetectionStrategy#OnPush(0) 把策略設為 CheckOnce(按需)。
· ChangeDetectionStrategy#Default(1) 把策略設定為 CheckAlways。
viewProviders Provider[] #定義一組可注入對象,它們在視圖的各個子節點中可用
moduleId string 包含該元件的那個模組的ID。此元件必須能解析模板和樣式表中使用的相對 URL。 SystemJS 在每個模組中都導出了 __moduleName 變數。在 CommonJS 中,它可以設定為module.id。
templateUrl string 元件範本檔案的 URL。如果提供了它,就不要再用 template 來提供內聯模板了。
template string 元件的內聯模板。如果提供了它,就不要再用 templateUrl 提供模板了。
styleUrls string[] 一個或多個 URL,指向包含本元件 CSS 樣式表的檔案。
styles string[] 本元件用到的一個或多個內嵌 CSS 樣式。
animations any[] 一個或多個動畫 trigger() 調用,包含一些 state() 和 transition() 定義。
encapsulation ViewEncapsulation 供模板和 CSS 樣式使用的樣式封裝策略。取值為:
· ViewEncapsulation.ShadowDom:使用 Shadow DOM。它只在原生支援 Shadow DOM 的平台上運作。
· ViewEncapsulation.Emulated:使用墊片(shimmed) CSS 來模擬原生行為。
· ViewEncapsulation.None:使用全域 CSS,不做任何封裝。
如果沒有提供,該值就會從 CompilerOptions 中取得它。預設的編譯器選項是 ViewEncapsulation.Emulated。如果該策略設定為 ViewEncapsulation.Emulated,且該元件沒有指定 styles 或 styleUrls,就會自動切換到 ViewEncapsulation.None。
interpolation [string, string] 改寫預設的插值表達式起止分界符({{ 和}})
entryComponents Array9eecf80e40e62541f9fe709ed995e8cd

以上是深入了解angular中的@Component裝飾器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除