在这个教程中,我们将学习如何使用 Angular 创建自定义组件和指令。组件是 Angular 的核心概念之一,它们允许我们以模块化的方式构建应用程序。指令则可以用来扩展 HTML 语法。

组件基础

组件是 Angular 的最小可复用单元。它们由模板、样式和逻辑组成。

创建组件

要创建一个组件,首先需要在模块中声明它:

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  // 组件逻辑
}

组件模板

组件模板定义了组件的界面。它通常包含 HTML 标签和 Angular 表达式。

<div>
  <h1>我的组件</h1>
  <p>{{ message }}</p>
</div>

组件样式

组件样式定义了组件的外观。你可以使用 CSS 来设置样式。

h1 {
  color: blue;
}

指令

指令是 Angular 中的另一个重要概念,它们可以用来扩展 HTML 语法。

属性指令

属性指令可以添加到元素上,并改变其行为。

<div appHighlight>
  这是高亮显示的文本
</div>
import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(true);
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(false);
  }

  highlight(isHighlight: boolean) {
    if (isHighlight) {
      this.hostElement.nativeElement.style.backgroundColor = 'yellow';
    } else {
      this.hostElement.nativeElement.style.backgroundColor = '';
    }
  }

  constructor(private hostElement: ElementRef) {}
}

学习资源

想要了解更多关于 Angular 组件和指令的知识,可以参考以下资源:

Angular Logo