推荐答案
在 Angular 中,常用的装饰器包括:
- @Component: 用于定义一个 Angular 组件。
- @Directive: 用于定义一个 Angular 指令。
- @Injectable: 用于定义一个 Angular 服务或依赖注入的类。
- @NgModule: 用于定义一个 Angular 模块。
- @Input: 用于将父组件的数据传递给子组件。
- @Output: 用于从子组件向父组件传递事件。
- @ViewChild: 用于在组件中获取对子组件或 DOM 元素的引用。
- @ContentChild: 用于在组件中获取对投影内容的引用。
- @HostBinding: 用于绑定宿主元素的属性。
- @HostListener: 用于监听宿主元素的事件。
本题详细解读
@Component
@Component 是 Angular 中最常用的装饰器之一,用于定义一个组件。它接受一个元数据对象,该对象包含组件的模板、样式、选择器等信息。
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'MyApp';
}@Directive
@Directive 用于定义一个指令。指令可以改变 DOM 元素的行为或外观。
// www.javascriptcn.com code example
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}@Injectable
@Injectable 用于定义一个服务或依赖注入的类。它告诉 Angular 这个类可以通过依赖注入系统进行注入。
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return 'Some data';
}
}@NgModule
@NgModule 用于定义一个 Angular 模块。模块是 Angular 应用的基本构建块,用于组织和管理组件、指令、管道和服务。
@NgModule({
declarations: [AppComponent, HighlightDirective],
imports: [BrowserModule],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule {}@Input
@Input 用于将父组件的数据传递给子组件。
@Component({
selector: 'app-child',
template: `<p>{{ childData }}</p>`
})
export class ChildComponent {
@Input() childData: string;
}@Output
@Output 用于从子组件向父组件传递事件。
// www.javascriptcn.com code example
@Component({
selector: 'app-child',
template: `<button (click)="sendData()">Send Data</button>`
})
export class ChildComponent {
@Output() dataEvent = new EventEmitter<string>();
sendData() {
this.dataEvent.emit('Data from child');
}
}@ViewChild
@ViewChild 用于在组件中获取对子组件或 DOM 元素的引用。
// www.javascriptcn.com code example
@Component({
selector: 'app-parent',
template: `<app-child #child></app-child>`
})
export class ParentComponent {
@ViewChild('child') childComponent: ChildComponent;
ngAfterViewInit() {
console.log(this.childComponent);
}
}@ContentChild
@ContentChild 用于在组件中获取对投影内容的引用。
// www.javascriptcn.com code example
@Component({
selector: 'app-parent',
template: `<ng-content></ng-content>`
})
export class ParentComponent {
@ContentChild('projectedContent') projectedContent: ElementRef;
ngAfterContentInit() {
console.log(this.projectedContent);
}
}@HostBinding
@HostBinding 用于绑定宿主元素的属性。
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor = 'yellow';
}@HostListener
@HostListener 用于监听宿主元素的事件。
// www.javascriptcn.com code example
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostListener('mouseenter') onMouseEnter() {
this.backgroundColor = 'yellow';
}
@HostListener('mouseleave') onMouseLeave() {
this.backgroundColor = 'transparent';
}
}