创建Angular组件
创建组件
ng g component components/header
使用组件
<app-header></app-header>
Angular绑定属性
<div[id]="id"[title]="msg">调试工具看看我的属性</div>
数据循环 *ngFor
<li *ngFor="let item of list">{{item}}</li>
<li *ngFor="let item of list;let i = index;"> {{item}} --{{i}} </li>
条件判断 *ngIf
<p *ngIf="list.length > 3">这是 ngIF 判断是否显示</p>
<p template="ngIf list.length > 3">这是 ngIF 判断是撒否显示</p>
执行事件 (click)=”getData()”
<button class="button" (click)="getData()"> 点击按钮触发事件 </button>
<button class="button" (click)="setData()"> 点击按钮设置数据 </button>
getData(){
/*自定义方法获取数据*/
alert(this.msg);
}
setData(){ //设置值 this.msg='这是设置的值'; }
表单事件
<input type="text" (keyup)="keyUpFn($event)"/>
keyUpFn(e){ console.log(e) }
双向数据绑定
<!-- input双向数据绑定 -->
<li>
<span>姓名:</span> <input type="text" [(ngModel)]="peopleInfo.username" >
</li>
<!-- radio双向数据绑定 -->
<li>
<span><input type="radio" id="sex1" value="1" [(ngModel)]="peopleInfo.sex"> <label for="sex1">男</label></span>
<span><input type="radio" id="sex2" value="2" [(ngModel)]="peopleInfo.sex"> <label for="sex2">女</label></span>
</li>
<!-- select双向数据绑定 -->
<li>
<select name="" id="" [(ngModel)]="peopleInfo.city">
<option [value]="item" *ngFor="let item of peopleInfo.citylist">{{item}}</option>
</select>
</li>
<!-- checkbox双向绑定 -->
<li>
<span *ngFor="let item of peopleInfo.hobby; let key=index">
<input type="checkbox" [id]="'checked'+'key'" [(ngModel)]="item.checked" > <label [for]="'checked'+'key'">{{item.title}}</label>
</span>
</li>
<li>
<button (click)="submitValue()">获取表单事件</button>
</li>
<!-- textarea双向绑定 -->
<li>
<textarea name="" id="" cols="30" rows="10" [(ngModel)]="peopleInfo.mark"></textarea>
</li>
<pre>
{{peopleInfo| json}}
</pre>
public peopleInfo: any = {
username: ''
};
// 可以直接获取双向绑定的值
submitValue() {
console.log(this.peopleInfo.username);
}
export class FromComponent implements OnInit {
public peopleInfo: any = {
username: '',
sex: '1',
citylist: ['北京', '上海', '深圳'],
city: '北京',
hobby: [{
title: '吃饭',
checked: false
}, {
title: '睡觉',
checked: false
}, {
title: '敲代码',
checked: true
}],
mark: ''
};
constructor() {
}
ngOnInit() {
}
submitValue() {
console.log(this.peopleInfo);
}
}
[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>
管道
public today=new Date();
<p>{{today | date:'yyyy-MM-dd HH:mm:ss' }}</p>