1、创建项目
安装:npm install -g @angular/cli
新建:ng new projectName
打开:ng serve —open
2、创建组件
创建组件:ng g component components/news
(在app下的components文件夹新建news组件,此种方式可以让app.module.ts自动引入此组件)
使用组件:在html中使用
3、app.module.ts详解
import { BrowserModule } from '@angular/platform-browser'; //浏览器解析模块import { NgModule } from '@angular/core'; //angular核心模块import { AppRoutingModule } from './app-routing.module'; //引入路由import { AppComponent } from './app.component'; //根组件import { NewsComponent } from './components/news/news.component'; //引入页面组件//@NgModule 装饰器,接收一个元数据对象,告诉Angular如何编译和启动应用@NgModule({declarations: [ //配置当前项目运行的组件AppComponent, NewsComponent],imports: [ //配置当前模块运行依赖的其他模块BrowserModule,AppRoutingModule],providers: [], //配置项目需要的服务bootstrap: [AppComponent] //指定应用的主视图(根组件),通过引导AppModule来启动应用,这里一般写的是根组件。})export class AppModule { } //根模块不需要到处任何东西,因为其他组件不需要导入根模块
4、声明数据—public protected private
在xxx.components.ts 中声明变量(属性),可以通过 {{title}} 引入
export class NewsComponent implements OnInit {public title:string = '我是一个新闻组件';//不加修饰符 默认为public、不加类型,默认为首次被赋值的类型,如果首次不赋值,默认为any//声明属性的方式://公有public 可以在当前类里访问 也可以在类外访问//保护protected 可以在当前类和其子类访问//私有private 只可以在当前类访问constructor() {//此处用于改变数据}ngOnInit() {}}
5、绑定数据—[]
//绑定数据<div [title]="student">鼠标放上</div>//绑定html<div [innerHTML]="content"></div>//绑定图片<img src="assets/images/文件说明.png" alt=""> //普通引入图片<img [src]="baiduImg" alt=""> //绑定数据引入图片
6、循环数据—*ngFor
<ul><li *ngFor="let item of userList;let key=index;trackBy:trackByUserList">{{item.name}}---{{item.age}}----索引{{key}}</li></ul>//components.ts中定义trackBy 用于优化diff算法trackByUserList(index: number, item: any): number { return item.id; }
7、条件判断—*ngIf
<div *ngIf="flag">{{test1}}</div><div *ngIf="!flag">{{test2}}</div>
8、[ngSwitch]、ngSwitchCase、ngSwitchDefault
<div [ngSwitch]="status"><div *ngSwitchCase="1">已支付</div><div *ngSwitchCase="2">已发货</div><div *ngSwitchCase="3">已收货</div><div *ngSwitchDefault>无效</div></div>
9、[ngClass]、[ngStyle]
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div><div [ngClass]="{'red':key==1,'blue':key==2}">This div is special</div><div [ngStyle]="{'background-color':'red'}"><div [style.font-size]="isSpecial ? 'x-large' : 'smaller'">
10、[(ngModel)] 双向数据绑定
在app.module.ts中引入FormsModule模块 才可以使用双向数据绑定
import { FormsModule } from '@angular/forms';@NgModule({imports: [FormsModule]})
在组件中使用
<input type="text" [(ngModel)]="student"><select name="city" id="city" [(ngModel)]="peopleInfo.city"><option [value]="item" *ngFor="let item of peopleInfo.cities">{{item}}</option></select>
11、管道
//component.tspublic today:any = new Date()//component.html{{today | date:'yyyy-mm-dd hh:mm:ss'}}
12、执行事件 — (click)
<button (click)="clickBtn()">按钮</button><input type="text" (keydown)="keyUp($event)">keyUp(e){console.log(e.target.value);}
