本篇文章主要介绍了剖析Angular Component的源码示例,写的十分的全面细致,具备必定的参考价值,对此有须要的朋友能够参考学习下。若有不足之处,欢迎批评指正。css
Web Componenthtml
定义前端
W3C为统一组件化标准方式,提出Web Component的标准。vue
每一个组件包含本身的html、css、js代码。 Web Component标准包括如下四个重要的概念: 1.Custom Elements(自定义标签):能够建立自定义 HTML 标记和元素; 2.HTML Templates(HTML模版):使用 标签去预约义一些内容,但并不加载至页面,而是使用 JS 代码去初始化它; 3.Shadow DOM(虚拟DOM):能够建立彻底独立与其余元素的DOM子树; 4.HTML Imports(HTML导入):一种在 HTML 文档中引入其余 HTML 文档的方法,。 node
归纳来讲就是,能够建立自定义标签来引入组件是前端组件化的基础,在页面引用 HTML 文件和 HTML 模板是用于支撑编写组件视图和组件资源管理,而 Shadow DOM 则是隔离组件间代码的冲突和影响。webpack
示例web
定义hello-component面试
<template id="hello-template">
<style>
h1 {
color: red;
}
</style>
<h1>Hello Web Component!</h1>
</template>
<script>
// 指向导入文档,即本例的index.html
var indexDoc = document;
// 指向被导入文档,即当前文档hello.html
var helloDoc = (indexDoc._currentScript || indexDoc.currentScript).ownerDocument;
// 得到上面的模板
var tmpl = helloDoc.querySelector('#hello-template');
// 建立一个新元素的原型,继承自HTMLElement
var HelloProto = Object.create(HTMLElement.prototype);
// 设置 Shadow DOM 并将模板的内容克隆进去
HelloProto.createdCallback = function() {
var root = this.createShadowRoot();
root.appendChild(indexDoc.importNode(tmpl.content, true));
};
// 注册新元素
var hello = indexDoc.registerElement('hello-component', {
prototype: HelloProto
});
</script>
复制代码
使用hello-componentbash
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-COMPATIBLE" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="赖祥燃, laixiangran@163.com, http://www.laixiangran.cn"/>
<title>Web Component</title>
<!--导入自定义组件-->
<link rel="import" href="hello.html" rel="external nofollow" >
</head>
<body>
<!--自定义标签-->
<hello-component></hello-component>
</body>
</html>
复制代码
从以上代码可看到,hello.html 为按标准定义的组件(名称为 hello-component ),在这个组件中有本身的结构、样式及逻辑,而后在 index.html 中引入该组件文件,便可像普通标签同样使用。app
Angular Component
Angular Component属于指令的一种,能够理解为拥有模板的指令。其它两种是属性型指令和结构型指令。 基本组成
@Component({
selector: 'demo-component',
template: 'Demo Component'
})
export class DemoComponent {}
复制代码
组件元数据
自身元数据属性
从 core/Directive 继承
几种元数据详解
如下几种元数据的等价写法会比元数据设置更简洁易懂,因此通常推荐的是等价写法。
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<false>();
}
复制代码
等价于:
@Component({
selector: 'demo-component'
})
export class DemoComponent {
@Output() ready = new eventEmitter<false>();
}
复制代码
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: `
<input #theInput type='text' />
<div>Demo Component</div>
`,
queries: {
theInput: new ViewChild('theInput')
}
})
export class DemoComponent {
theInput: ElementRef;
}
复制代码
等价于:
@Component({
selector: 'demo-component',
template: `
<input #theInput type='text' />
<div>Demo Component</div>
`
})
export class DemoComponent {
@ViewChild('theInput') theInput: ElementRef;
}
复制代码
queries - 内容查询
<my-list>
<li *ngFor="let item of items;">{{item}}</li>
</my-list>
@Directive({
selector: 'li'
})
export class ListItem {}
@Component({
selector: 'my-list',
template: `
<ul>
<ng-content></ng-content>
</ul>
`,
queries: {
items: new ContentChild(ListItem)
}
})
export class MyListComponent {
items: QueryList<ListItem>;
}
复制代码
等价于:
@Component({
selector: 'my-list',
template: `
<ul>
<ng-content></ng-content>
</ul>
`
})
export class MyListComponent {
@ContentChild(ListItem) items: QueryList<ListItem>;
}
复制代码
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使用构造函数新建组件后,就会按下面的顺序在特定时刻调用这些生命周期钩子方法:
结语
感谢您的观看,若有不足之处,欢迎批评指正。
本次给你们推荐一个免费的学习群,里面归纳移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。 对web开发技术感兴趣的同窗,欢迎加入Q群:864305860,无论你是小白仍是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时天天更新视频资料。 最后,祝你们早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。