This time I will bring you a detailed explanation of the practical skills of Angular Component. What are theprecautionswhen using Angular Component? The following is a practical case, let’s take a look.
Web Component
Before introducing Angular Component, let’s briefly understand W3C Web Components
Definition
W3C proposes the standard of Web Component to unify the standard way of componentization.
Each component contains its own html, css, and js code.
Web Component standard includes the following four important concepts:
1.Custom Elements (custom tags): You can create custom HTML tags and elements;
2.HTML Templates (HTML templates): use < ;template> tag to predefine some content, but it does not load it into the page, but uses JS code to initialize it;
3.Shadow DOM (virtual DOM): You can create a DOM subtree that is completely independent from other elements;
4.HTML Imports: A method of introducing other HTML documents into HTML documents,.
In summary, the ability to create custom tags to introduce components is the basis for front-end componentization. References to HTML files and HTML templates on the page are used to support writing component views and component resource management, while Shadow DOM It is to isolate the conflicts and impacts of code between components.
Example
Define hello-component
Hello Web Component!
Use hello-component
As you can see from the above code, hello. html is a component defined by standards (named hello-component). This component has its own structure, style and logic. Then introduce the component file in index.html and use it like an ordinary tag.
Angular Component
Angular Component is a type of directive and can be understood as a directive with a template. The other two types are attribute directives and structural directives.
Basic composition
@Component({ selector: 'demo-component', template: 'Demo Component' }) export class DemoComponent {}
Component decorator: Each component class must be decorated with @component to become an Angular component.
Component metadata: Component metadata: selector, template, etc. The following will focus on the meaning of each metadata.
Component class: Component is actually an ordinary class, and the logic of the component is defined and implemented in the component class.
Component template: Each component will be associated with a template, which will eventually be rendered on the page. The DOM element on the page is the host element of this component instance.
Component metadata
Self metadata attributes
Inherited from core/Directive
Name | Type | Function |
---|---|---|
AnimationEntryMetadata[] | Set the animation of the component | |
ChangeDetectionStrategy | Set the change detection strategy of the component | |
ViewEncapsulation | Set the view packaging options of the component | |
any[] | Set the list of components that will be dynamically inserted into the component view | |
[string, string] | Interpolation mark of custom component, the default is double curly brackets | |
string | Set the module id of the component under the ES/CommonJS specification, which is used to resolve the relative path of the template style | |
string[] | Set the external style file referenced by the component | |
string[] | Set the inline style used by the component | |
string | Set the inline template of the component | |
string | Set the path to the component template | |
Provider[] | Set the services available to the component and all its subcomponents (excluding ContentChildren) |
几种元数据详解
以下几种元数据的等价写法会比元数据设置更简洁易懂,所以一般推荐的是等价写法。
inputs
@Component({ selector: 'demo-component', inputs: ['param'] }) export class DemoComponent { param: any; }
等价于:
@Component({ selector: 'demo-component' }) export class DemoComponent { @Input() param: any; }
outputs
@Component({ selector: 'demo-component', outputs: ['ready'] }) export class DemoComponent { ready = new eventEmitter(); }
等价于:
@Component({ selector: 'demo-component' }) export class DemoComponent { @Output() ready = new eventEmitter(); }
host
@Component({ selector: 'demo-component', host: { '(click)': 'onClick($event.target)', // 事件 'role': 'nav', // 属性 '[class.pressed]': 'isPressed', // 类 } }) export class DemoComponent { isPressed: boolean = true; onClick(elem: HTMLElement) { console.log(elem); } }
等价于:
@Component({ selector: 'demo-component' }) export class DemoComponent { @HostBinding('attr.role') role = 'nav'; @HostBinding('class.pressed') isPressed: boolean = true; @HostListener('click', ['$event.target']) onClick(elem: HTMLElement) { console.log(elem); } }
queries - 视图查询
@Component({ selector: 'demo-component', template: `Demo Component
`, queries: { theInput: new ViewChild('theInput') } }) export class DemoComponent { theInput: ElementRef; }
等价于:
@Component({ selector: 'demo-component', template: `Demo Component
` }) export class DemoComponent { @ViewChild('theInput') theInput: ElementRef; }
queries - 内容查询
{{item}}
@Directive({ selector: 'li' }) export class ListItem {}
@Component({ selector: 'my-list', template: `
等价于:
@Component({ selector: 'my-list', template: `
styleUrls、styles
styleUrls和styles允许同时指定。
优先级:模板内联样式 > styleUrls > styles。
建议:使用styleUrls引用外部样式表文件,这样代码结构相比styles更清晰、更易于管理。同理,模板推荐使用templateUrl引用模板文件。
changeDetection
ChangeDetectionStrategy.Default:组件的每次变化监测都会检查其内部的所有数据(引用对象也会深度遍历),以此得到前后的数据变化。
ChangeDetectionStrategy.OnPush:组件的变化监测只检查输入属性(即@Input修饰的变量)的值是否发生变化,当这个值为引用类型(Object,Array等)时,则只对比该值的引用。
显然,OnPush策略相比Default降低了变化监测的复杂度,很好地提升了变化监测的性能。如果组件的更新只依赖输入属性的值,那么在该组件上使用OnPush策略是一个很好的选择。
encapsulation
ViewEncapsulation.None:无 Shadow DOM,并且也无样式包装。
ViewEncapsulation.Emulated:无 Shadow DOM,但是通过Angular提供的样式包装机制来模拟组件的独立性,使得组件的样式不受外部影响,这是Angular的默认设置。
ViewEncapsulation.Native:使用原生的 Shadow DOM 特性。
当Angular使用构造函数新建组件后,就会按下面的顺序在特定时刻调用这些生命周期钩子方法:
生命周期钩子 | 调用时机 |
---|---|
ngOnChanges | 在ngOnInit之前调用,或者当组件输入数据(通过@Input装饰器显式指定的那些变量)变化时调用。 |
ngOnInit | 第一次ngOnChanges之后调用。建议此时获取数据,不要在构造函数中获取。 |
ngDoCheck | 每次变化监测发生时被调用。 |
ngAfterContentInit | 使用 |
ngAfterContentChecked | ngAfterContentInit后被调用,或者每次变化监测发生时被调用(只适用组件)。 |
ngAfterViewInit | 创建了组件的视图及其子视图之后被调用(只适用组件)。 |
ngAfterViewChecked | ngAfterViewInit,或者每次子组件变化监测时被调用(只适用组件)。 |
ngOnDestroy | 销毁指令/组件之前触发。此时应将不会被垃圾回收器自动回收的资源(比如已订阅的观察者事件、绑定过的DOM事件、通过setTimeout或setInterval设置过的计时器等等)手动销毁掉。 |
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of practical skills of Angular Component. For more information, please follow other related articles on the PHP Chinese website!