十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
组件是 Angular 应用的主要构造块。每个组件包括如下部分:

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名与空间、雅安服务器托管、营销软件、网站建设、龙胜网站维护、网站推广。
本主题描述如何创建和配置 Angular 组件。
要查看或下载本主题中使用的范例代码,请参阅 现场演练 / 下载范例。
要创建一个组件,请先验证你是否满足以下先决条件:
ng new  创建一个,其中 Angular CLI 是用来创建组件的最简途径。你也可以手动创建一个组件。
使用 Angular CLI 创建一个组件:
ng generate component  命令,其中 默认情况下,该命令会创建以下内容:
.component.ts  .component.html  .component.css  .component.spec.ts  其中 
你可以更改 
ng generate component 创建新组件的方式。
虽然 Angular CLI 是创建 Angular 组件的最佳途径,但你也可以手动创建一个组件。本节将介绍如何在现有的 Angular 项目中创建核心组件文件。
要手动创建一个新组件:
.component.ts import { Component } from '@angular/core';import 语句之后,添加一个 @Component 装饰器。@Component({
})@Component({
  selector: 'app-component-overview',
})@Component({
  selector: 'app-component-overview',
  templateUrl: './component-overview.component.html',
})@Component({
  selector: 'app-component-overview',
  templateUrl: './component-overview.component.html',
  styleUrls: ['./component-overview.component.css']
})class 语句。export class ComponentOverviewComponent {
}每个组件都需要一个 CSS 选择器。选择器会告诉 Angular:当在模板 HTML 中找到相应的标签时,就把该组件实例化在那里。例如,考虑一个组件 hello-world.component.ts ,它的选择器定义为 app-hello-world 。 当 
在 @Component 装饰器中添加一个 selector 语句来指定组件的选择器。
@Component({
  selector: 'app-component-overview',
})模板是一段 HTML,它告诉 Angular 如何在应用中渲染组件。可以通过以下两种方式之一为组件定义模板:引用外部文件,或直接写在组件内部。
要把模板定义为外部文件,就要把 templateUrl 添加到 @Component 装饰器中。
@Component({
  selector: 'app-component-overview',
  templateUrl: './component-overview.component.html',
})要在组件中定义模板,就要把一个 template 属性添加到 @Component 中,该属性的内容是要使用的 HTML。
@Component({
  selector: 'app-component-overview',
  template: 'Hello World!
',
})如果你想让模板跨越多行,可以使用反引号( ` )。例如:
@Component({
  selector: 'app-component-overview',
  template: `
    Hello World!
    This template definition spans multiple lines.
  `
})Angular 组件需要一个用 
template或 templateUrl定义的模板。但你不能在组件中同时拥有这两个语句。
有两种方式可以为组件的模板声明样式:引用一个外部文件,或直接写在组件内部。
要在单独的文件中声明组件的样式,就要把 styleUrls 属性添加到 @Component 装饰器中。
@Component({
  selector: 'app-component-overview',
  templateUrl: './component-overview.component.html',
  styleUrls: ['./component-overview.component.css']
})要想在组件内部声明样式,就要把 styles 属性添加到 @Component,该属性的内容是你要用的样式。
@Component({
  selector: 'app-component-overview',
  template: 'Hello World!
',
  styles: ['h1 { font-weight: normal; }']
})styles 属性接受一个包含 CSS 规则的字符串数组。