创建项目:ng new angulardemo1
运行项目:ng serve --open
创建组件:ng g component components/home
声明属性的几种方式:
- public : 共有 (默认) 可以在这个类里面使用,也可以在类外面使用
- protected : 保护类型 只有在当前类和它的自雷里面可以访问
- private : 私有 只有在当前类才可以访问这个属性
绑定数据
<h1>angular模板里面绑定数据</h1>
<h2>{{title}}</h2>
<h2>{{userinfo.username}}</h2>
<h1>angular模板里面绑定属性</h1>
<div title="我是一个div">
鼠标瞄上去看一下
</div>
<div [title]="student">
张三
</div>
<h1>angular模板里面绑定HTML</h1>
<!-- ts里
this.h = "<h2>这是一个h2用[innerHTML]来解析</h2>"
-->
<div [innerHTML]="h">
</div>
angular的数据运算
1+2={{1+2}}
angular里面的数据循环
//定义数组
arr = ['111','222','333'];
//推荐
public list:any[]=['我是一个新闻',222223,'第三个'];
public items:Array<any>=['我是一个新闻',222223,'第三个'];
<ul>
<li *ngFor="let item of arr">
{{item}}
</li>
</ul>
引入图片
<img src="assets/images/1.png" alt="收藏"/>
<img [src]="picUrl"/>
循环数据,显示数据的索引
public list:any[]=[
{
"title":"新闻1"
},
{
"title":"新闻2"
},
{
"title":"新闻3"
}
]
<ul>
<li *ngFor="let item of list;let key=index">
{{key}} ------{{item.title}}
</li>
</ul>
条件判断 *ngIf
ngSwitch *ngSwitchCase
ngClass
<div class="red">
ngClass演示 (尽量不要用dom来改变class)
</div>
<div [ngClass]="{'blue':true,'red':false}">
ngClass 演示
</div>
<div [ngClass]="{'blue':flag,'red':!flag}">
ngClass 演示
</div>
<strong>循环数组</strong>
<li *ngFor="let item of list;let key=index;" [ngClass]="{'red':key==0,'orange':key==1,'blue':key==2}">
{{key}} ------{{item.title}}
</li>
ngStyle
<p style="color:red">普通样式表达</p>
<p [ngStyle]="{'color':'blue'}">
单引号---固定值
</p>
<p [ngStyle]="{'color':attr}">
引用ts 值
</p>
管道
public today:any = new Date();
<p>
{{today | date:'yyyy-MM-dd HH:mm:ss'}}
</p>
其他管道:
http://bbs.itying.com/topic/5bf519657e9f5911d41f2a34
事件
public title:string="一个title"
run(){
alert('这是一个自定义方法');
}
getDate(){
alert(this.title);
}
setDate(){
this.title="改变后的title";
}
runEvent(event){
dom:any = event.target;
dom.style.color="red";
}
<strong>{{title}}</strong>
<button (click)="run()">执行事件</button>
<button (click)="getDate()">执行方法获取数据</button>
<button (click)="setDate()">执行方法改变属性里面的数据</button>
表单事件
keyDown(e){
if(e.keyCode==13){
console.log('按了一下回车');
}else{
//e.target 获取dom对象
console.log(e.target.value);
}
}
keyUp(e){
if(e.keyCode==13){
console.log(e.target.value);
console.log('按了一下回车');
}
}
keyDown
<input type="text" (keydown)="keyDown($event)"/>
双向数据绑定----MVVM 只针对表单
首先,引入 FormsModule 在app.module.ts中
再声明:imports:[..,FormsModule]
public keywords:string='这是默认值';
changeKeywords(){
this.keywords='改变后的值';
}
getKeywords(){
console.log(this.keywords);
}
<input type='text' [(ngModel)]='keywords'/>{{keywords}}
<button (click)="changeKeywords()">
改变keywords的值
</button>
<button (click)="getKeywords()">
获取keywords的值
</button>
浙公网安备 33010602011771号