【Angular】 组件(Component)

在 Angular 中,组件(Component) 是构建用户界面的基本单位。每个 Angular 应用通常由多个组件组成,组件负责显示视图、处理用户交互以及管理应用逻辑。组件不仅包含 HTML 模板、CSS 样式,还包含 TypeScript 代码,它们一起构成了 Angular 应用的基本模块。

组件的基本结构

每个组件由以下几个部分组成:

  1. TypeScript 文件 (.ts):定义组件的类和逻辑。
  2. HTML 模板文件 (.html):定义组件的视图部分。
  3. CSS 文件 (.css.scss 等):定义组件的样式。
  4. 组件装饰器@Component):标注组件类,告诉 Angular 这是一个组件,并提供有关该组件的元数据。

创建组件

在 Angular 中,你可以使用 Angular CLI 来生成组件:

ng generate component component-name

# 简写
ng g c component-name

这会在 src/app 目录下生成一个新的组件文件夹,包含以下内容:

  • component-name.component.ts:组件的 TypeScript 类文件。
  • component-name.component.html:组件的 HTML 模板文件。
  • component-name.component.css:组件的 CSS 样式文件。
  • component-name.component.spec.ts:组件的单元测试文件。

组件的结构和代码示例

1. 组件类(TypeScript 文件)

每个组件类定义了该组件的逻辑,通常包括:

  • 组件的输入(Input)和输出(Output)
  • 组件的生命周期钩子
  • 数据绑定逻辑
import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',  // 组件的标签名,用于在 HTML 中引用
  templateUrl: './my-component.component.html',  // 组件的模板文件
  styleUrls: ['./my-component.component.css']  // 组件的样式文件
})
export class MyComponent {
  title: string = 'Hello, Angular!';

  // 组件的方法
  changeTitle() {
    this.title = 'Title changed!';
  }
}
  • @Component 装饰器

    :用于标注类为 Angular 组件,并提供组件的元数据。

    • selector:定义组件的 HTML 标签(例如 <app-my-component></app-my-component>)。
    • templateUrl:指向组件的 HTML 模板文件。
    • styleUrls:指向组件的样式文件。
2. 模板文件(HTML 文件)

模板文件定义了该组件的视图部分,它包含 HTML 代码,并支持 Angular 特有的模板语法,如数据绑定、指令等。

<div>
  <h1>{{ title }}</h1>
  <button (click)="changeTitle()">Change Title</button>
</div>
  • 数据绑定:使用 {{ title }} 实现数据绑定,将组件的 title 属性绑定到视图中。
  • 事件绑定:使用 (click) 来处理点击事件,调用 changeTitle() 方法。
3. 样式文件(CSS 或 SCSS 文件)

每个组件都可以拥有自己的样式,这些样式仅对该组件生效(视为封闭样式)。这使得样式更加模块化和可维护。

h1 {
  color: blue;
}

button {
  background-color: lightblue;
}

组件的输入与输出(Input 和 Output)

组件的 输入输出 使得组件之间能够共享数据和事件。

1. 输入(@Input)

@Input 装饰器允许父组件向子组件传递数据。

// 子组件 (child.component.ts)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<p>{{ message }}</p>`
})
export class ChildComponent {
  @Input() message: string;  // 接收来自父组件的数据
}

父组件传递数据给子组件:

<!-- 父组件 (parent.component.html) -->
<app-child [message]="parentMessage"></app-child>
// 父组件 (parent.component.ts)
export class ParentComponent {
  parentMessage = 'Hello from Parent!';
}
2. 输出(@Output)

@Output 装饰器允许子组件向父组件发送事件。

// 子组件 (child.component.ts)
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Hello from Child!');
  }
}

父组件接收子组件的事件:

<!-- 父组件 (parent.component.html) -->
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>{{ message }}</p>
// 父组件 (parent.component.ts)
export class ParentComponent {
  message: string;

  receiveMessage($event: string) {
    this.message = $event;
  }
}

组件生命周期钩子

Angular 组件有一系列的生命周期钩子,用于在组件的不同阶段执行代码。这些钩子方法在组件的生命周期中自动被调用。

常用的生命周期钩子包括:

  • ngOnInit():组件初始化时调用,通常用于获取数据。
  • ngOnChanges():当组件输入属性发生变化时调用。
  • ngOnDestroy():组件销毁时调用,用于清理资源。
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-lifecycle',
  template: `<p>Lifecycle hooks example</p>`
})
export class LifecycleComponent implements OnInit, OnDestroy {

  ngOnInit() {
    console.log('ngOnInit: Component initialized!');
  }

  ngOnDestroy() {
    console.log('ngOnDestroy: Component destroyed!');
  }
}

组件的嵌套和复用

Angular 组件是可以嵌套和复用的。父组件可以包含多个子组件,通过数据绑定和事件来进行通信。子组件可以通过多个父组件复用,并且组件可以组合成复杂的用户界面。

总结

  1. 组件是 Angular 的基本构建单元:它们将视图(HTML)、样式(CSS)和逻辑(TypeScript)组合在一起。
  2. 组件使用 @Component 装饰器进行标识,并指定组件的模板和样式。
  3. 数据绑定:Angular 提供了强大的数据绑定机制,包括插值绑定、属性绑定、事件绑定和双向绑定。
  4. 组件间的通信:使用 @Input@Output 实现父子组件之间的通信。
  5. 生命周期钩子:Angular 提供了一组生命周期钩子,允许你在组件的不同阶段运行代码。
  6. 组件的复用与嵌套:组件可以嵌套和复用,提高开发效率。

Angular 的组件化架构使得开发者可以将复杂的用户界面分解成独立的、可管理的小组件,使得应用更加模块化、可维护。

### Angular 中 `@Component` 装饰器详解 #### 功能概述 在 Angular 应用程序中,组件是构建用户界面的核心要素之一。`@Component` 是一种特殊的装饰器,用于定义 Angular 组件类[^3]。 #### 基本结构 一个典型的 `@Component` 装饰器通常包含以下几个属性: - **selector**: 定义如何在模板中选择此组件实例。它类似于 CSS 选择器语法。 - **template** 或 **templateUrl**: 指定组件视图的 HTML 结构。可以直接提供字符串形式的模板或者指向外部文件路径。 - **styleUrls** 或 **styles**: 提供附加到该组件的样式表链接或内联样式规则列表。 示例如下所示: ```typescript import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { } ``` #### 高级配置选项 除了上述基本参数外,还可以利用其他高级特性来自定义行为: - **encapsulation**: 控制样式的封装模式,默认情况下采用 Emulated 方式[^4]。这三种方式分别是 None, Emulated 和 Native。 ```typescript encapsulation: ViewEncapsulation.Emulated, ``` - **changeDetection**: 设置变更检测策略以优化性能表现。 ```typescript changeDetection: ChangeDetectionStrategy.OnPush, ``` - **providers**: 注册服务提供商以便于依赖注入操作。 ```typescript providers: [MyService], ``` #### 实际应用案例 下面是一个完整的例子展示了如何创建并注册一个新的 Angular 组件: ```typescript import { Component } from '@angular/core'; @Component({ selector: 'welcome-message', template: `<h1>Hello {{name}}!</h1>`, styles: [`h1 { font-family: Arial; color: blue; }`] }) export class WelcomeMessageComponent { name = 'World'; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值