深入了解angular中的@Component装饰器

来自:互联网
时间:2022-05-28
阅读:

一、 @Component 装饰器

1.1 @Component 装饰器的用途

声明一个组件时,在组件类的之上要用@Component装饰器来告知Angular这是一个组件。

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product-alerts',
  templateUrl: './product-alerts.component.html',
  styleUrls: ['./product-alerts.component.CSS']
})
export class ProductAlertsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

1.2 @Component 装饰器的常用选项

@Component 装饰器继承于 Directive ,这个css选择器用于在模板中标记出该指令,并触发该指令的实例化。

1.2.1 继承自@Directive装饰器的选项

选项 类型 说明
selector string css选择器名,用于在模板中标记出该指令(组件),并触发其实例化
inputs string[] Angular 会在变更检测期间自动更新输入属性。inputs 属性定义了一组从 directiveProperty 指向 bindingProperty 的配置项:
· directiveProperty 用于指定要写入值的指令内属性。
· bindingProperty 用于指定要从中读取值的 DOM 属性。当没有提供 bindingProperty 时,就假设它和 directiveProperty 一样。
outputs string[] 一组可供事件绑定的输出属性。当输出属性发出事件时,就会调用模板中一个附加到该事件的处理器。每个输出属性都会把 directiveProperty 映射到 bindingProperty:
· directiveProperty 指定要发出事件的组件属性。
· bindingProperty 指定要附加事件处理器的 HTML 属性。
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自己特有的选项

选项 类型 说明
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 Array<Type any[]>
preserveWhitespaces boolean 为 true 则保留,为 false 则从编译后的模板中移除可能多余的空白字符。 空白字符就是指那些能在 JavaScript 正则表达式中匹配 \s 的字符。默认为 false,除非通过编译器选项改写了它。

二、 selector 选择器

可使用下列形式之一:

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

2.1 element-name: 根据元素名选取

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

2.2 [attribute]: 根据属性名选取

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

2.3 .class: 根据类名选取

@Component({
    selector: '.app-element',
    template:  './element.component.html',
    styleUrls: ['./element.component.css']
})
<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 attribute 和 property

  • 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 使用 host 绑定 class

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

3.3 使用 host 绑定 style

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

3.4 使用 host 绑定事件

@Component({
    selector: '.app-element',
    template:  './element.component.html',
    styleUrls: ['./element.component.css'],
    host: {
        '(click)': 'onClick($event)'
    }
})
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('.shadowhost');
 // 创建影子根(shadow root)
 var shadowRoot = shadowHost.createShadowRoot();
 // 影子根作为影子树的第一个节点,其他的节点比如p节点都是它的子节点。
 shadowRoot.innerHTML = '<p>我在 Shadow Host内</p>';
</script>
</body>
<html>

4.3 ViewEncapsulation

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

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

4.3.1 ViewEncapsulation.None

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'my-app',
  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 = 'Semlinker';
}

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

4.3.2 ViewEncapsulation.Emulated

import { Component, ViewEncapsulation } from '@angular/core';

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

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 '@angular/core';

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

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

返回顶部
顶部