Avatar ·

@Directive和@Component在Angular中的区别:何时使用哪个?

大家好!我开始学习Angular和TypeScript,在创建我的第一个组件和指令时,我对`@Component`和`@Directive`装饰器之间的区别感到困惑。文档中说`@Component`是`@Directive`的子类,但在实践中它们的使用方式不同。 例如,我创建一个简单的按钮,在悬停时改变颜色。我可以通过组件和指令两种方式实现。这是我的代码: **使用@Component的版本:** ```typescript import { Component } from '@angular/core'; @Component({ selector: 'app-hover-button', template: ``, styles: [` .highlight { background-color: yellow; } `] }) export class HoverButtonComponent { onHover() { /* 添加class */ } onLeave() { /* 移除class */ } } ``` **使用@Directive的版本:** ```typescript import { Directive, HostListener, HostBinding } from '@angular/core'; @Directive({ selector: '[appHover