1.模块与装潢器
Angular设想目的就是顺应大型运用的开辟,模块的观点就是来组织差别的组件及效劳。一个大型运用的终究形状就是种种差别的模块的组合
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HeroService } from './hero.service';
//NgModule装潢器将AppModule类标记为Angular组件
@NgModule({
//装潢器就是一个函数,作用是将元数据添加到紧跟在后面的类、类成员(属性、要领)和函数参数
imports: [ BrowserModule ], //导入本模块中所须要的其他非自定义的模块
providers: [ HeroService ], //效劳模块,并自动加入到全局的效劳列表中
declarations: [ AppComponent ], //声明本模块中的组件,指令和管道
bootstrap: [ AppComponent ] //根组件,
})
export class AppModule { } //导出的根模块
2.组件、指令、管道
组件在Angular中处于中间职位,但也是指令的一种,我把组件看作是含有模板的指令,管道就是anuglarjs中的过滤器,详细有哪几种,能够参考Anugular的官方API Angular内置管道
自定义组件
import { Component } from '@angular/core';
@Component({ //@Component装潢器将HeroDetailComponent类标记为Angular组件
//内部的数据称为元数据,别的元数据装潢器用相似的体式格局来指点 Angular 的行动。
//比方@Injectable、@Input、@Output等
selector: 'hero-detail',
templateUrl: '../somewhere.html',
styleUrls: ['./any.css']
})
export class HeroDetailComponent {
//仅仅是一个类,看不到Anugular框架的影子
}
自定义指令
//指令有属性型指令和结构型指令 和组件
import { Directive, ElementRef, Input } from '@angular/core';
//ElementRef注入到组织函数中,如许指令才接见DOM
//Input 将数据传入指令中
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
自定义管道
<p>The hero's birthday is {{ birthday | date:'yyyy.MM.dd' }}</p>
<p>The current pipe {{ somevalue | paramStrength:'number' }}</p>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'paramStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
//implements是一品种完成某个接口的写法,如许就能够运用对应接口内里的要领,如这里的transform
transform(value: number, params: string): number {
//value是输入值,params是传入的参数
//value对应上面的somevalue, params对应上面的number
let exp = parseFloat(exponent);
return value + exp ;
}
}
3.效劳
效劳能够为对数据的猎取和种种处置惩罚,组件就是效劳的消费者,经由过程依靠注入在组件中运用效劳
import { Injectable } from '@angular/core';
import { Logger } from '../logger.service';
@Injectable({})
export class HeroService {
//效劳内里注入其他的效劳,经由过程依靠注入,相当于执行了new的操纵,又没有副作用
constructor(private logger: Logger){}
}
4.生命周期
就是被Anuglar治理的组件的生命周期钩子,对应的有钩子内里的要领
import { OnInit, OnDestroy } from '@angular/core';
//OnInit接口内里的ngOnInit要领
export class PeekABoo implements OnInit, OnDestroy {
constructor() { }
// implement OnInit's `ngOnInit` method
ngOnInit() {
console.log("组件初始化");
}
ngOnDestroy(){
console.log("组件退出时完成的要领");
}
}