Component is a subclass of Directive. It is a decorator used to mark a class as aAngularcomponent. The following article will give you an in-depth understanding of the @Component decorator in angular. I hope it will be helpful to you.
@Component
Decorator1.1@Component
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 '@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
Common options for decorators
@Component
The decorator inherits fromDirective
. This css selector is used to mark the directive in the template. and triggers the instantiation of this directive.
1.2.1Options inherited from @Directive decorator
Options | Type | Description |
---|---|---|
selector | string | css selector name, used in templates Mark the directive (component) in and trigger its instantiation |
inputs | string[] | 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. |
outputs | string[] | 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. |
provides | Provider[] | A collection of service providers |
exportAs | string | One 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. |
jit | true | If 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
selector
选择器可使用下列形式之一:
element-name
: 根据元素名选取[attribute]
: 根据属性名选取.class
: 根据类名选取[attribute=value]
: 根据属性名和属性值选取not(sub_selector)
: 只有当元素不匹配子选择器 sub_selector 的时候才选取selector1, selector2
: 无论 selector1 还是 selector2 匹配时都选取2.1element-name
: 根据元素名选取
@Component({ selector: 'app-element', template: './element.component.html', styleUrls: ['./element.component.css'] })
2.2[attribute]
: 根据属性名选取
@Component({ selector: '[app-element]', template: './element.component.html', styleUrls: ['./element.component.css'] })
2.3.class
: 根据类名选取
@Component({ selector: '.app-element', template: './element.component.html', styleUrls: ['./element.component.css'] })
host
:{[key:string]:string}
使用一组键-值对,把类的属性映射到宿主元素的绑定(Property、Attribute 和事件)。
Angular 在变更检测期间会自动检查宿主 Property 绑定。 如果绑定的值发生了变化,Angular 就会更新该指令的宿主元素。
对于事件处理:
3.1attribute
和property
异同:
所以在 angular2 中双向
绑定实现是由dom 的 property
实现的,所以指令绑定的是 property ,但是在某些情况下 dom 不存在某个 property 比如 colspan,rowspan 等,这时想要绑定 html 标签特性需要用到attr
:
Month | Savings |
---|---|
January | |
February |
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; }
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'; }
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); } }
encapsulation
(封装)供模板和 CSS 样式使用的样式封装策略。
4.1 Web Components
通过一种标准化的非侵入的方式封装一个组件,每个组件能组织好它自身的 HTML 结构、CSS 样式、JavaScript 代码,并且不会干扰
页面上的其他元素。
Web Components 由以下四种技术组成:
4.2 Shadow DOM
4.3ViewEncapsulation
ViewEncapsulation 允许设置三个可选的值:
4.3.1ViewEncapsulation.None
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'my-app', template: `Welcome to Angular World
Hello {{name}}
`, 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.2ViewEncapsulation.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.3ViewEncapsulation.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 形式渲染
。
更多编程相关知识,请访问:编程视频!!
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!
Type | Description | |
---|---|---|
ChangeDetectionStrategy | When 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: | · ChangeDetectionStrategy#OnPush(0) Sets the strategy to CheckOnce (on demand). · ChangeDetectionStrategy#Default(1) Set the strategy to CheckAlways. |
Provider[] | Define a set of injectable objects that are available in various child nodes of the view | |
string | The 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. | |
string | The URL of the component template file. If it is provided, do not use template to provide inline templates. | |
string | The inline template of the component. If it is provided, do not use templateUrl to provide the template. | |
string[] | One or more URLs pointing to the file containing the CSS style sheet of this component. | |
string[] | One or more inline CSS styles used by this component. | |
any[] | One or more animation trigger() calls, containing some state() and transition() definitions. | |
ViewEncapsulation | Style encapsulation strategy used by templates and CSS styles. The values are: | · 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. |
[string, string] | Override the default start and end delimiters of interpolation expressions ({ | { and }}) |
Array | ||
## 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. |