@Component
Decorator1.1 Purpose of @Component
Decorator
When declaring a component, the @Component decorator must be used on the component class to tell Angular that this is a component. [Related tutorial recommendation: "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 Common options of @Component
decorator
@Component
decorator inherits from Directive
. This css selector is used to mark the directive in the template and trigger the instantiation of the directive.
1.2.1继承自@Directive装饰器的选项
type | description | selector |
---|---|---|
string | css | selector name, used to mark the directive (component) in the template and trigger its instantiation |
inputs | string[] | Angular will automatically during change detection Update input properties. The inputs attribute defines a set of configuration items pointing from directiveProperty to bindingProperty: · directiveProperty is used to specify the property within the directive to which the value is 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 attribute 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} | configures 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 instruction/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} | uses a set of key-value pairs to map class properties to host element 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 the key is a Property of the host element, the Property value will be 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 handling: · Its key is the DOM event that the instruction 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, 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自己特有的选项
Option | type | description | |
---|---|---|---|
changeDetection | 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 policy is one of the following values: · ChangeDetectionStrategy#OnPush(0) sets the strategy to CheckOnce (on demand). · ChangeDetectionStrategy#Default(1) sets the strategy to CheckAlways. | |
viewProviders | Provider[] | defines a set of injectable objects that are available in each child node of the view. | |
moduleId | string | contains the ID of the module that contains the 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. | |
templateUrl | stringThe | URL of the component template file. If it is provided, do not use template to provide inline templates. | |
The inline template of the | template | string | component.If it is provided, do not use templateUrl to provide the template. |
styleUrls | string[] | One or more URLs, pointing to the file containing the CSS style sheet of this component. | |
styles | string[] | One or more inline CSS styles used by this component. | |
animations | any[] | One or more animation trigger() calls, containing some state() and transition() definitions. | |
encapsulation | ViewEncapsulation | is a 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 is 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 will automatically switch to ViewEncapsulation.None. | |
interpolation | [string, string] | overrides the default start and end delimiters of interpolation expressions ({ { and }}) | |
entryComponents | Array<Type | any[]> | |
preserveWhitespaces | boolean | If true, it is retained, if 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. |
selector
selectorcan use one of the following forms:
element-name
: select[attribute]
based on the element name: select.class
based on the attribute name: select [attribute=value] based on the class namenot(sub_selector)
[attribute=value]
on the attribute name and attribute valuenot(sub_selector)
: select selector1, selector2 only when the element does not match the sub-selector sub_selectorselector1, selector2
2.1 is selected whether selector1 or selector2 matches element-name
: select
@Component({ selector: 'app-element', template: './element.component.html', styleUrls: ['./element.component.css'] })
<app-element></app-element>
2.2 [attribute]
: Select
@Component({ selector: '[app-element]', template: './element.component.html', styleUrls: ['./element.component.css'] })
<div app-element></div>
2.3 .class
: Select
@Component({ selector: '.app-element', template: './element.component.html', styleUrls: ['./element.component.css'] })
<div class="app-element"></div>
host
: {[key:string]:string}
uses a set of key-value pairs to map the properties of the class to the binding of the host element (Property , Attributes and events).
Angular automatically checks host Property bindings during change detection. If the bound value changes, Angular updates the directive's host element.
for event processing:
3.1 attribute
and property
Similarities and differences:
Therefore,双向
binding implementation in angular2 is implemented by dom 的property
, so the instruction is bound to the property, but in some cases the dom does not exist. Property such as colspan, rowspan, etc. If you want to bind html tag properties, you need to use 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 Use host
to bind class
@Component({ selector: '.app-element', template: './element.component.html', styleUrls: ['./element.component.css'], host: { '[class.default-class]': 'useDefault' }, encapsulation: ViewEncapsulation.None // Let the host element also use element.component.css style. Otherwise, capsules are used by default to avoid CSS pollution. }) export class AppElementComponent { @Input() useDefault = true; }
<div class="app-element"></div>
3.3 Use host
binding 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 Use host
to bind events
@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
(encapsulation)Style encapsulation strategy for templates and CSS styles.
4.1 Web Components
encapsulate a component in a standardized and non-intrusive way. Each component can organize its own HTML structure, CSS style, and JavaScript code without不会干扰
other elements on the page.
Web Components consists of the following four technologies:
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>I am not in Shadow Host</p> <div>Hello, world!</div> <script> // shadow host var shadowHost = document.querySelector('.shadowhost'); // Create shadow root (shadow root) var shadowRoot = shadowHost.createShadowRoot(); // The shadow root is the first node of the shadow tree, and other nodes such as the p node are its child nodes. shadowRoot.innerHTML = '<p>I am in Shadow Host</p>'; </script> </body> <html>
4.3 ViewEncapsulation
ViewEncapsulation allows setting three optional values:
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'; }
The result of setting ViewEncapsulation.None
is that there is no Shadow DOM
, and all styles are applied to整个
document
. In other words, the style of the component will受外界影响
and may be覆盖
.
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'; }
The result of the ViewEncapsulation.Emulated
setting is that there is no Shadow DOM
, but the component is encapsulated through样式包装机制
provided by Angular
so that the component's style不受外部影响
. Although the style is still applied to整个document
, Angular creates a [_ngcontent-cmy-0]
selector for the .greet
class. It can be seen that为组件定义的样式,被Angular 修改了
. Among them, _nghost-cmy- 和_ngcontent-cmy-
are used to实现局部的样式
.
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'; }
The result of the ViewEncapsulation.ShadowDom
setting is to use the native Shadow DOM
feature. Angular will Shadow DOM 形式渲染
supported by the browser.