Angular 中的 @Directive 与 @Component [英] @Directive vs @Component in Angular
问题描述
Angular 中的 @Component
和 @Directive
有什么区别?他们似乎都在做同样的任务,拥有同样的属性.
有哪些用例以及何时更喜欢一种?
@Component 需要视图,而@Directive 不需要.
指令
我将 @Directive 比作带有选项 的 Angular 1.0 指令(指令不限于属性使用.)指令将行为添加到现有的 DOM 元素或现有的组件实例.指令的一个示例用例是记录对元素的点击.restrict: 'A'
import {Directive} from '@angular/core';@指示({选择器:[logOnClick]",主机监听器:{'点击': 'onClick()',},})类登录点击{构造函数(){}onClick() { console.log('元素被点击!');}}
会像这样使用:
组件
一个组件,而不是添加/修改行为,实际上创建了自己的视图(DOM 元素的层次结构)和附加的行为.一个示例用例可能是联系人卡片组件:
import {Component, View} from '@angular/core';@成分({选择器:'联系卡',模板:`<div><h1>{{name}}</h1><p>{{city}}</p>
`})类联系人卡片{@Input() 名称:字符串@Input() 城市:字符串构造函数(){}}
会像这样使用:
<contact-card [name]="'foo'" [city]="'bar'"></contact-card>
ContactCard
是一个可重用的 UI 组件,我们可以在应用程序的任何地方使用它,甚至可以在其他组件中使用.这些基本上构成了我们应用程序的 UI 构建块.
总结
当您想要创建一组可重用的具有自定义行为的 UI DOM 元素时,请编写一个组件.当您想编写可重用行为来补充现有 DOM 元素时,请编写指令.
来源:
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?
A @Component requires a view whereas a @Directive does not.
Directives
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!'); }
}
Which would be used like so:
<button logOnClick>I log when clicked!</button>
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() {}
}
Which would be used like so:
<contact-card [name]="'foo'" [city]="'bar'"></contact-card>
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.
In summary
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.
Sources:
这篇关于Angular 中的 @Directive 与 @Component的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!