Home > Web Front-end > JS Tutorial > body text

Deep understanding of @Component decorator in angular

青灯夜游
Release: 2022-05-30 11:14:27
forward
3117 people have browsed it

Component is a subclass of Directive. It is a decorator used to mark a class as a Angular component. The following article will give you an in-depth understanding of the @Component decorator in angular. I hope it will be helpful to you.

Deep understanding of @Component decorator in angular

1. @Component Decorator

1.1 <span style="font-size: 18px;">@Component</span> Purpose of decorator

When declaring a component, use the @Component decorator on top of the component class. Tells Angular that this is a component. [Related tutorial recommendations: "angular tutorial"]

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() {
  }

}
Copy after login

1.2 <span style="font-size: 18px;">@Component</span> Common options for decorators

@Component The decorator inherits from Directive. This css selector is used to mark the directive in the template. and triggers the instantiation of this directive.

1.2.1 Options inherited from @Directive decorator

OptionsTypeDescription
selectorstringcss selector name, used in templates Mark the directive (component) in and trigger its instantiation
inputsstring[]Angular will automatically update during change detection Enter attributes. The inputs attribute defines a set of configuration items pointing from directiveProperty to bindingProperty:
· directiveProperty is used to specify the properties within the directive to which values ​​are to be written.
· bindingProperty is used to specify the DOM property from which the value is to be read. When bindingProperty is not provided, it is assumed to be the same as directiveProperty.
outputsstring[]A set of output properties for event binding. When an output property emits an event, a handler in the template attached to the event is called. Each output property maps directiveProperty to bindingProperty:
· directiveProperty specifies the component property to emit the event.
· bindingProperty specifies the HTML property to which the event handler is to be attached.
providesProvider[]A collection of service providers
exportAsstringOne or more names that can be used to assign this directive to a variable in the template. When there are multiple names, separate them with commas.
queries{[key:string]:any}Configure some queries that will be injected into this directive. The content query is set before calling the ngAfterContentInit callback. The view query will be set before calling the ngAfterViewInit callback.
jittrueIf true, the directive/component will be ignored by the AOT compiler, so it will always be JIT compiled . This option is to support future Ivy compilers and has no effect yet.
host{[key:string]:string}Use a set of key-value pairs to map class attributes to host elements Bindings (Properties, Attributes, and Events). Angular automatically checks host Property bindings during change detection. If the bound value changes, Angular updates the directive's host element. When key is a Property of the host element, the Property value is propagated to the specified DOM attribute. When the key is a static Attribute in the DOM, the Attribute value will be propagated to the Property specified on the host element. For event processing:
· Its key is the DOM event that the directive wants to listen to. To listen to a global event, add the target you want to listen to in front of the event name. The target can be window, document, or body.
· Its value is the statement to be executed when the event occurs. If this statement returns false, then the preventDefault function of this DOM event will be called. The local variable $event can be referenced in this statement to obtain event data.

1.2.2 @Component’s own options

##OptionsTypeDescriptionchangeDetectionChangeDetectionStrategyWhen the component is instantiated, Angular will create a change detector , which is responsible for propagating changes in each binding value of the component. The strategy is one of the following values: viewProvidersProvider[]Define a set of injectable objects that are available in various child nodes of the viewmoduleIdstringThe ID of the module that contains this component. The component must be able to resolve relative URLs used in templates and stylesheets. SystemJS exports the __moduleName variable in every module. In CommonJS, this can be set to module.id. templateUrlstringThe URL of the component template file. If it is provided, do not use template to provide inline templates. templatestringThe inline template of the component. If it is provided, do not use templateUrl to provide the template. styleUrlsstring[]One or more URLs pointing to the file containing the CSS style sheet of this component. stylesstring[]One or more inline CSS styles used by this component. animationsany[]One or more animation trigger() calls, containing some state() and transition() definitions. encapsulationViewEncapsulationStyle encapsulation strategy used by templates and CSS styles. The values ​​are: interpolation[string, string]Override the default start and end delimiters of interpolation expressions ({entryComponentsArrayany[]>preserveWhitespaces

二、 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;]
})
Copy after login
<app-element></app-element>
Copy after login

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;]
})
Copy after login
<div app-element></div>
Copy after login

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;]
})
Copy after login
<div class="app-element"></div>
Copy after login
Copy after login
Copy after login
Copy after login

三、 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;
Copy after login

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;
}
Copy after login
<div class="app-element"></div>
Copy after login
Copy after login
Copy after login
Copy after login

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;;
}
Copy after login
<div class="app-element"></div>
Copy after login
Copy after login
Copy after login
Copy after login

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);
  }
}
Copy after login
<div class="app-element"></div>
Copy after login
Copy after login
Copy after login
Copy after login

四、 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>
Copy after login

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;;
}
Copy after login

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;;
}
Copy after login

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;;
}
Copy after login

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

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

The above is the detailed content of Deep understanding of @Component decorator in angular. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
· ChangeDetectionStrategy#OnPush(0) Sets the strategy to CheckOnce (on demand).
· ChangeDetectionStrategy#Default(1) Set the strategy to CheckAlways.
· ViewEncapsulation.ShadowDom: Use Shadow DOM. It only works on platforms that natively support Shadow DOM.
· ViewEncapsulation.Emulated: Use shimmed CSS to emulate native behavior.
· ViewEncapsulation.None: Use global CSS without any encapsulation.
If not provided, the value will be obtained from CompilerOptions. The default compiler option is ViewEncapsulation.Emulated. If the policy is set to ViewEncapsulation.Emulated and the component does not specify styles or styleUrls, it automatically switches to ViewEncapsulation.None.
{ and }})
## If #boolean is true, it is retained, and if it is false, possible extra whitespace characters are removed from the compiled template. Whitespace characters are those characters that match \s in JavaScript regular expressions. Defaults to false unless overridden via compiler options.