component 是 Angular UI 的基本构建块——一个用 @Component 装饰器装饰的 TypeScript class,用于控制屏幕的一个部分(它的"view")。每个 Angular 应用都是一个 components 树。
组件的构成
ts
{ } ;
({
: ,
: ,
: [],
})
{
name = ;
() { ; }
}
component 是 Angular UI 的基本构建块——一个用 @Component 装饰器装饰的 TypeScript class,用于控制屏幕的一个部分(它的"view")。每个 Angular 应用都是一个 components 树。
{ } ;
({
: ,
: ,
: [],
})
{
name = ;
() { ; }
}
@Component 装饰器将三件事联系在一起:selector(你在 HTML 中如何使用它)、template(标记)和 styles(作用范围限于该组件)。
<!-- user-card.html — the template binds to the class -->
<h2>{{ name }}</h2> <!-- interpolate a property -->
<button (click)="greet()">Greet</button> <!-- call a method on click -->
类的公共属性和方法可以通过绑定直接在其 template 中访问——这是 Angular 连接数据和视图的核心方式。
<!-- in another component's template, use the selector -->
<app-user-card></app-user-card>
/* user-card.css — these styles ONLY affect this component */
h2 { color: blue; } /* won't leak to other components' <h2>s */
Angular 自动限定组件样式的作用范围(View Encapsulation),因此 CSS 不会在组件之间泄漏。
Components 是构建每个 Angular 应用的方式——模板 + 逻辑 + 作用范围限制的样式的自包含单元,组合成一棵树。
理解 @Component 装饰器(selector、template、styles)以及类的属性/方法如何与 template 绑定是 Angular 开发的绝对基础;其他一切都建立在组件模型之上。