1.HTML文件
循环数据 显示数据索引(key)
ul>
<li *ngFor="let item of list let key=index;">
let key=index;意思是将angular的索引赋值给key
{{key}} {{item.title}}
</li>
</ul>
Ts文件
public list:any[]=[
{
"title":'我是标题一'
},
{
"title":'我是标题二'
},
{
"title":'我是标题三'
}
]
- *ngIf判断语句用法
<div *ngIf="flag">
<img src="assets/images/01.jpg" alt="hello">
</div>
<div *ngIf!="flag">
<img src="assets/images/02.jpg" alt="hi">
</div>
public flag:boolean=true;
- *ngSwitch用法
HTML文件
<span [ngSwitch]="Orderstates">
<p *ngSwitchCase="1">已支付</p>
<p *ngSwitchCase="2">已支付并确认订单</p>
<p *ngSwitchCase="3">已发货</p>
<p *ngSwitchCase="4">确认收货</p>
<p *ngSwitchDefault>无效订单</p>
</span>
typescript
public Orderstates:number=5;
4.属性[ngclass],[ngstyle]
[ngClass]
HTML
<div [ngClass]="{red: true}">my name is songna and my english name is Nina</div>
<div [ngClass]="{'red':!flag,'blue':flag}">my name is songna and my english name is Nina</div>
<strong>循环数组让数组的第一个样式为红色</strong>
<ul>
<li *ngFor="let item of list,let key=index;"[ngClass]="{'red':key==0,'green':key==1}">
{{key}}{{item.title}}
</li>
</ul>
typescript``
public list:any[]=[
{
"title":'我是标题一'
},
{
"title":'我是标题二'
},
{
"title":'我是标题三'
}
];
public flag:boolean=false;
[ngStyle]
<p [ngStyle]="{color:'green'}">hello</p>
<p [ngStyle]="{color:cor}">hi</p>
typescript
public cor:string='green';
5.管道
angular中的管道以及自定义管道
例:
HTML
{{today|date:'yyyy-MM-dd'}}
typescript
public today:any=new Date();
- 事件
<button (click)="run()">点击</button>
<!-- 获取数据 -->
<button (click)="getdate()">2</button>
<!-- 修改数据 -->
<button (click)="setdate()">3</button>
Ts
public title: string = '这是没改变前的title';
getdate(){
alert(this.title) ;
}
setdate(){
this.title = '这是改变后得值';
}
- 双向绑定数据[(ngModel)]
- 双向数据绑定MVVM意思就是model变了view就会变view变了model也会变,双向数据绑定只针对表单
<input type ="text" [(ngModel)]='username' />
{{username}}
<button (click)="changeusername()">变</button>
-
这个就能很好地展示MVVM text框中的值变了外面username的值肯定也会随之改变
-
在使用之前一定要先在app.model.ts文件中引入模块然后再声明才可以正常使用
import { FormsModule } from '@angular/forms';
imports: [
FormsModule
],
在ts文件中定义一个方法
public userInfo: any = {
username: ''
}
然后再HTML文件中用[(ngModel)]来用那个方法获取数据
<li>姓名:<input type="text" id="username" [(ngModel)]="userInfo.username")] /> </li>