@Directive v / s @Component in Angular [英] @Directive v/s @Component in Angular
问题描述
Angular中的 @Component
和 @Directive
有什么区别?
它们似乎都执行相同的任务并具有相同的属性。
What is the difference between @Component
and @Directive
in Angular?
Both of them seem to do the same task and have the same attributes.
有什么用例以及何时优先选择另一个?
What are the use cases and when to prefer one over another?
推荐答案
@Component需要一个视图,而@Directive则不需要。
我将@Directive比作Angular 1.0指令,选项(指令不限于属性使用。)指令将行为添加到现有DOM元素或现有组件实例。指令的一个示例用例是记录元素上的点击。 restrict:'A'
I liken a @Directive to an Angular 1.0 directive with the option (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.restrict: 'A'
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元素的层次结构)。一个示例用例可能是联系卡组件:
Components
A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:
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构建块。
ContactCard
is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.
当你想要的时候写一个组件使用自定义行为创建可重用的UI DOM元素集。如果要编写可重用行为以补充现有DOM元素,请编写指令。
Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.
来源:
- @Directive documentation
- @Component documentation
- Helpful blog post
这篇关于@Directive v / s @Component in Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!