项目结构
一 创建特性模块,及其包含的组件、服务。
ng g module art
ng g component art/music
ng g component art/dance
ng g service art/performance
二 特性模块
art.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MusicComponent } from './music/music.component';
import { DanceComponent } from './dance/dance.component';
import { PerformanceService } from './performance.service'; @NgModule({
imports: [
CommonModule
],
// 把特性模块和组件关联起来:添加专属于这个模块的可声明对象(组件、指令和管道)
declarations: [MusicComponent, DanceComponent],
// 导出组件:导入特性模块后,就可以使用其中包含的组件模版了
exports: [
MusicComponent,
DanceComponent
],
providers: [
PerformanceService
]
})
export class ArtModule { }
三 组件
music.component.ts
import { Component, OnInit, Input } from '@angular/core'; @Component({
selector: 'app-music',
templateUrl: './music.component.html',
styleUrls: ['./music.component.css']
})
export class MusicComponent implements OnInit { @Input()
name: string; constructor() { } ngOnInit() {
} }
music.component.html
<p>
music works!{{name}}
</p>
dance.component.ts
import { Component, OnInit, Input } from '@angular/core'; @Component({
selector: 'app-dance',
templateUrl: './dance.component.html',
styleUrls: ['./dance.component.css']
})
export class DanceComponent implements OnInit { @Input()
name: string; constructor() { } ngOnInit() {
} }
dance.component.html
<p>
dance works!{{name}}
</p>
四 服务
performance.service.ts
import { Injectable } from '@angular/core'; @Injectable()
export class PerformanceService { constructor() { } perform(): string[] {
return ['唱歌', '跳舞'];
}
}
五 导入特性模块
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core'; import { AppComponent } from './app.component';
import { ArtModule } from './art/art.module'; @NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ArtModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
六 使用特性模块的组件、服务
app.component.ts
import { Component } from '@angular/core';
import { PerformanceService } from './art/performance.service'; @Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { constructor(public performance: PerformanceService) { }
perform() {
console.log(this.performance.perform());
}
}
app.component.html
<p>
app works!
</p>
<!-- 单向绑定:组件的属性 -->
<app-music [name]="'水边的阿狄丽娜'"></app-music>
<!-- 单向绑定:值是固定的,故使用一次性绑定 ( a "one-time" binding ) -->
<app-dance name="踢踏舞"></app-dance>
<button type="button" (click)="perform();">演出</button>
七 运行效果