1.使用[(ngModel)]="name",必须选择使用FormsModule
模块
虽然NgModel
是一个有效的Angular指令,但它默认情况下却是不可用的。 它属于一个可选模块FormsModule
。 我们必须选择使用那个模块。
在app.module.ts文件中
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule // <-- import the FormsModule before binding with [(ngModel)]
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
2.ngFor
<li *ngFor="let hero of heroes">
ngFor
的*
前缀表示<li>
及其子元素组成了一个主控模板。
ngFor
指令在AppComponent.heroes
属性返回的heroes
数组上迭代,并输出此模板的实例。
引号中赋值给ngFor
的那段文本表示“从heroes
数组中取出每个英雄,存入一个局部的hero
变量,并让它在相应的模板实例中可用”。
3.事件
<li *ngFor="let hero of heroes" (click)="onSelect(hero)"> ... </li>
圆括号标识<li>
元素上的click
事件是绑定的目标。 等号右边的onSelect(hero)
表达式调用AppComponent
的onSelect()
方法,并把模板输入变量hero
作为参数传进去。
4.*ngIf="selectedHero"
5.<li [class.selected]="hero === selectedHero" > </li>
6.命名
文件名:hero-detail.component.ts(大驼峰形式,并且以Component
结尾)
组件类名:HeroDetailComponent(小写中线形式,每个单词之间用中线分隔,并且以.component.ts
结尾)
7.组件
import { Component } from '@angular/core';
@Component({
selector: 'hero-detail',
})
export class HeroDetailComponent {
}
要定义一个组件,我们总是要先导入符号Component
。
@Component
装饰器为组件提供了Angular元数据。 CSS选择器的名字hero-detail
会匹配元素的标签名,用于在父组件的模板中标记出当前组件的位置。
总是export
这个组件类,因为你必然会在别处import
它。
父组件与子组件之间的通信(父组件是列表页,子组件是详情页)
父组件的模板中:<hero-detail [hero]="selectedHero"></hero-detail>
子组件:import { Component, Input } from '@angular/core';
export class HeroDetailComponent { @Input() hero: Hero; }
然后在子组件的模板中就能用hero.xxx了
它所做的一切就是通过它的输入属性hero
接收一个英雄对象,然后把这个属性绑定到自己的模板中。
具体参照父子组件之间通信http://blog.csdn.net/u010730126/article/details/68080139
8.定义的组件要在AppModule中声明
import { HeroDetailComponent } from './hero-detail.component';
把HeroDetailComponent
添加到该模块的declarations
数组中。
declarations: [
AppComponent,
HeroDetailComponent
],
9.创建服务
命名:文件名:special-super-hero.service.ts 服务名:SpecialSuperHeroService
import { Injectable } from '@angular/core';
@Injectable()
export class HeroService {
}
我们导入了 Angular 的Injectable
函数,并作为@Injectable()
装饰器使用这个函数。
当 TypeScript 看到@Injectable()
装饰器时,就会记下本服务的元数据。 如果 Angular 需要往这个服务中注入其它依赖,就会使用这些元数据。
导入HeroService
import { HeroService } from './hero.service';
在运行中获得一个具体的HeroService
实例
注入 HeroService
-
添加一个构造函数,并定义一个私有属性。
-
添加组件的
providers
元数据。
constructor(private heroService: HeroService) { }
我们还得注册一个HeroService
提供商,来告诉注入器如何创建HeroService
。 要做到这一点,我们在@Component
组件的元数据底部添加providers
数组属性如下:
10.如何创建服务并使用
一.新建一个服务my-comp.service.ts及使用方法
import{Injectable}from'@angular/core';
@Injectable()
export classMyCompService{
constructor() {}
hello(){
console.log(3456)
alert(3456)
}
}
二,创建服务
在app.module.ts,引入服务,在declarations中声名服务,并在provides中注册服务
三,在组件函数中调用服务
注册
import{MyCompService}from'./my-comp.service';
使用
constructor(private serves: MyCompService){
serves.hello();
}