3.1 component.ts 里面定义数据
/*
声明属性的几中方式
public 共有 * (默认) 可以在这个类里面使用,也可以在类外面使用
protected 保护类型 它只有在当前的类和它的子类中可以访问
private 私有 只有在当前类才可以访问这个属性
*/
// 定义普通数据
public title = '我是新闻组件';
msg = '我是新闻组件的msg';
username:string = '张三';
// 推荐写法
public student:string = '我是一个学生的属性(数据)';
public userinfo:object = {
"username":'张三',
'age':'20'
}
public message:any;
public content = "<h2>我是一个HTML标签</h2>";
// 定义数组
public arr = ['111','222','333'];
// 定义数组的方式
// 推荐
public items:any[] = ['我是第一个新闻',2222222222,'我是第三个新闻'];
public list:Array<string> = ['我是第一个新闻','2222222222','我是第三个新闻'];
public userlist:any[] = [
{
username:'张三',
age:'20'
},
{
username:'李四',
age:'21'
},
{
username:'王五',
age:'40'
}
];
3.2 Angular 绑定数据
1) 数据文本绑定
<h1> {{title}} </h1>
2) 绑定 html
Public h:any;
this.h="<h2>这是一个 h2 用[innerHTML]来解析</h2>"
<div [innerHTML]="h"></div>
3.3 Angular 绑定属性
<div [id]="id" [title]="msg">调试工具看看我的属性</div>
3.4 数据循环 *ngFor
3.4.1 *ngFor 普通循环
定义数据:
Public list:any[] = [1,2,3,4,,5,6];
循环
<ul> <li *ngFor="let item of list"> {{item}} </li> </ul>
3.4.2 循环的时候设置 key
<ul> <li *ngFor="let item of list;let key = index;"> {{ item }} --{{ key }} </li> </ul>
3.4.3 template 循环数据
<ul> <li template="ngFor let item of list"> {{item}} </li> </ul>
3.5 条件判断
<p *ngIf="list.length > 3">这是 ngIF 判断是否显示</p>
<p template="ngIf list.length > 3">这是 ngIF 判断是否显示</p>
<ul [ngSwitch]="score">
<li *ngSwitchCase="1">已支付</li>
<li *ngSwitchCase="2">订单已经确认</li>
<li *ngSwitchCase="3">已发货</li>
<li *ngSwitchDefault>无效</li>
</ul>
3.6 执行事件
<button class="button" (click)="getData()"> 点击按钮触发事件 </button>
.ts文件
getData(){ /*自定义方法获取数据*/ //获取 alert(this.msg);
}
3.7 表单事件
<input type="text" (keyup)="keyUpFn($event)"/>
keyUpFn(e){
console.log(e)
}
3.8 双向数据绑定
注意引入:FormsModule
import { FormsModule } from '@angular/forms';
注册
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent ],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [
AppComponent
]
})
export class AppModule { }
使用:
<input type="text" [(ngModel)]="inputValue"/>
{{inputValue}}
3.9 [ngClass]、[ngStyle]
<div [ngClass]="{'red': true, 'blue': false}">
这是一个 div
</div>
public flag=false;
<div [ngClass]="{'red': flag, 'blue': !flag}">
这是一个 div
</div>
public arr = [1, 3, 4, 5, 6];
<ul>
<li *ngFor="let item of arr, let i = index">
<span [ngClass]="{'red': i==0}">{{item}}</span>
</li>
</ul>
<div [ngStyle]="{'background-color':'green'}">你好 ngStyle</div>
public attr='red'; <div [ngStyle]="{'background-color':attr}">你好 ngStyle</div>