@Component
和@Directive
在Angular 上有什么区别?
什么是用例,什么时候更喜欢一个而不是另一个?
@Component
和@Directive
在Angular 上有什么区别?
什么是用例,什么时候更喜欢一个而不是另一个?
A @Component requires a view whereas a @Directive does not.
我将@Directive比作带有选项restrict: 'A'
的Angular 1.0指令(指令不限于属性用法)指令向现有DOM元素或现有组件实例添加行为.指令的一个示例用例是记录对元素的点击.
import {Directive} from '@angular/core';
@Directive({
selector: "[logOnClick]",
hostListeners: {
'click': 'onClick()',
},
})
class LogOnClick {
constructor() {}
onClick() { console.log('Element clicked!'); }
}
这样使用:
<button logOnClick>I log when clicked!</button>
组件不是添加/修改行为,而是创建自己的视图(DOM元素的层次 struct )和附加的行为.这方面的一个示例用例可能是联系人卡组件:
import {Component, View} from '@angular/core';
@Component({
selector: 'contact-card',
template: `
<div>
<h1>{{name}}</h1>
<p>{{city}}</p>
</div>
`
})
class ContactCard {
@Input() name: string
@Input() city: string
constructor() {}
}
这样使用:
<contact-card [name]="'foo'" [city]="'bar'"></contact-card>
ContactCard
是一个可重用的UI组件,我们可以在应用程序中的任何地方使用,甚至在其他组件中也可以使用.这些基本上构成了我们应用程序的UI构建块.
当您想要创建一组具有自定义行为的可重用的UI DOM元素时,请编写一个组件.当您想要编写可重用行为以补充现有DOM元素时,请编写一条指令.
资料来源: