在Angular 10中,模型类装饰器用于给类添加一些特殊的行为或功能。常用的模型类装饰器有三个:@Component、@Directive和@Injectable。
@Component装饰器用于将一个类标记为一个组件,并告诉Angular如何处理这个组件。它接受一个配置对象作为参数,用于指定组件的元数据,例如选择器、模板、样式等。
以下是一个使用@Component装饰器的示例:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: 'Example Component
',
styles: ['h1 { color: red; }']
})
export class ExampleComponent {
// 组件逻辑
}
@Directive装饰器用于将一个类标记为一个指令,并告诉Angular如何处理这个指令。它接受一个配置对象作为参数,用于指定指令的元数据,例如选择器、宿主元素、事件等。
以下是一个使用@Directive装饰器的示例:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appExampleDirective]'
})
export class ExampleDirective {
constructor(private el: ElementRef) {}
@HostListener('click') onClick() {
this.el.nativeElement.style.color = 'red';
}
}
@Injectable装饰器用于将一个类标记为一个可注入的服务,并告诉Angular如何创建这个服务的实例。它没有接受任何参数。
以下是一个使用@Injectable装饰器的示例:
import { Injectable } from '@angular/core';
@Injectable()
export class ExampleService {
// 服务逻辑
}
这是Angular 10中常用的几个模型类装饰器示例,它们分别用于标记组件、指令和服务,并告诉Angular如何处理它们。根据具体的需求,你可以选择使用适当的装饰器来定义和配置你的类。