Angular 主要分为八大构造块(也就是八个核心概念):模块 (module)、组件 (component)、模板 (template)、元数据 (metadata)、数据绑定 (data binding)、指令 (directive)、服务 (service)、依赖注入 (dependency injection)。其中,最核心的一个概念就就组件。
1. 模块 (module)
Angular 应用是模块化的,并且 Angular 有自己的模块系统,它被称为 Angular 模块或 NgModules。
每个Angular应用至少有一个模块(根模块),习惯上命名为AppModule。
根模块在一些小型应用中可能是唯一的模块,大多数应用会有很多特性模块,每个模块都是一个内聚的代码块专注于某个应用领域、工作流或紧密相关的功能。
Angular 模块(无论是根模块还是特性模块)都是一个带有@NgModule装饰器的类。
下面是一个简单的根模块:
// src/app/app.module.tsimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';@NgModule({ imports: [ BrowserModule ], providers: [ Logger ], declarations: [ AppComponent ], exports: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }
其中重要的属性是:
2. 组件 (component)
组件负责控制屏幕上的一小块区域,我们称之为视图。
下面是一个组件的简单例子:
// src/app/hero-list.component.tsexport class HeroListComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; constructor(private service: HeroService) { } ngOnInit() { this.heroes = this.service.getHeroes(); } selectHero(hero: Hero) { this.selectedHero = hero; }}
3. 模板 (template)
模板就是HTML文件,但是不是标准的HTML文件,它使用了一些模板语法,模板语法使模板有了自己的逻辑关系,并能够实现和组件的简单数据交互。
下面是一个简单的模板:
// src/app/hero-list.component.html<h2>Hero List</h2><p><i>Pick a hero from the list</i></p><ul> <li *ngFor="let hero of heroes" (click)="selectHero(hero)"> {{hero.name}} </li></ul><hero-detail *ngIf="selectedHero" [hero]="selectedHero"></hero-detail>
新闻热点
疑难解答
图片精选