组件
组件是 Angular 应用程序最基本的 UI 构建块。一个 Angular 应用程序包含一个 Angular 组件树。我们在 Angular 中的应用程序是建立在 组件树 之上的。每个组件都应该有它的模板、样式、生命周期、选择器等。所以,每个组件都有它的结构您可以将它们视为一个独立的小型 Web 应用程序,具有自己的模板和逻辑,并且可以与其他组件通信并一起使用。
组件的示例 .ts 文件:
import { Component } from '@angular/core';
@Component({
// component attributes
selector: 'app-training',
templateUrl: './app-training.component.html',
styleUrls: ['./app-training.component.less']
})
export class AppTrainingComponent {
title = 'my-app-training';
}
及其 ./app.component.html 模板视图:
Hello {{title}}
然后你可以在其他组件中渲染 AppTrainingComponent 模板及其逻辑(添加到模块后)
<div>
<app-training></app-training>
</div>
结果是
<div>
my-app-training
</div>
因为 AppTrainingComponent 在这里渲染
见more about Components
指令
指令更改现有 DOM 元素的外观或行为。例如 [ngStyle] 是一个指令。指令可以扩展组件(可以在其中使用),但它们不会构建整个应用程序。假设它们只支持组件。 它们没有自己的模板(当然,您可以使用它们来操作模板)。
示例指令:
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@Input('appHighlight') highlightColor: string;
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor || 'red');
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
及其用法:
<p [appHighlight]="color" [otherPar]="someValue">Highlight me!</p>
见more about directives