@Directive与@Component在Angular中 [英] @Directive vs @Component in Angular
问题描述
@Component
和@Directive
在Angular中有什么区别?
他们两个似乎都执行相同的任务,并具有相同的属性.
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与@Component在Angular中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!