angular2--常用标签[(ngModel)]、*ngFor、*ngIf等等

常用标签

一、跳转事件

html:

<div (click)="goPage('prevPage')"></div>   //跳转到上一页
<div (click)="goPage('nextPage')"></div>   //跳转到下一页

ts:

//路径仅供参考,引入跳转到的页面
import {PrevPage} from '../../../prevPage/prevPage';
import {NextPage} from '../../../nextPage/nextPage';


goPage(type) {
	switch(type) {
		case 'prevPage':
			this.navigator.nativeElement.popPage();
		break;
		case 'nextPage':
			this.navigator.nativeElement.pushPage(NextPage, {animation: 'slide',data: {aaa: 'bbb'}});
		break;
		default:
			console.log('Not Founded In The Router');
	}
}

二、跳转事件传参,接收参数

在跳转事件的例子里,我们的跳转函数带了参数,那在接收页面怎么打印出来呢:

this.navigator.nativeElement.pushPage(Index, {animation: 'slide',data: {aaa: 'bbb'}});

angular2有很多钩子函数,我们在constructor函数里接收:
ts:

constructor(private navigator: OnsNavigator,private eventBus: EventServices,
		private httpService: HttpService,
		private settingService: SettingService,
		private _params:Params ) {
			console.log(this._params.data);   //打印出传进来的参数
}

三、数据的双向绑定

html:

<input type="text" id="name" [(ngModel)]="name" />
<p>{{name}}</p>

ts:

public name:String="";

在这里插入图片描述

四、数据循环渲染

html:

<div>
	<p *ngFor="let list of lists">{{name}}</p>
</div>

ts:

lists =[
	{
		id:1,
		name:"你好"
	},
	{
		id:2,
		name:"你好"
	}
]

五、if条件判断

html:

//常用来做内容是否显示的控制
<p *ngIf="isBack==true">我回来啦</p>
<p *ngIf="isBack==false">我还没有回来</p>

ts:

isBack:any=false;

我用得最多的就是用它来设置选项卡:
html:

<div class="r-cnt">
	<ul class="r-ul clearfix">
		<li *ngFor="let tab of tabs" (click)="chooseTab(tab.id)" [ngClass]="{'active':tabId==tab.id}">{{tab.name}}</li>
	</ul>
	<div *ngIf="tabId==1">
		你好
	</div>
	<div *ngIf="tabId==2">
		哈哈
	</div>
	<div *ngIf="tabId==3">
		嘻嘻
	</div>
</div>

css:

.r-ul{
	border-bottom: 1px solid #f2f2f2;
	display: flex;
	justify-content: space-around;
	align-items: center;
}

.r-ul li{
	padding: 10px 8px;
	text-align: center;
	color: #4a4a4a;
	
}

.r-ul li.active{
	color: #4a90e2;
	border-bottom: 1px solid #4a90e2;
}

.clearfix{
	content: '';
	clear: both;
	display: block;
	overflow: hidden;
}

ts:

tabs = [
	{
		id: 1,
		name: "推荐"
	},
	{
		id: 2,
		name: "最新"
	},
	{
		id: 3,
		name: "热门"
	}
]
	tabId = 1;
	chooseTab(type) {
		this.tabId = type;
	}

在这里插入图片描述

六、父子组件传值

angular2经常会把一个通用的组件封装为component,如:test-item,在前端使用的时候只需要这么写<test-item></test-item>就可以使用了。但有时候经常会涉及到向组件传值的情况,要怎么实现呢?

比如我现在在test.html里面使用了组件:
<test-item></test-item>

那么test.html就是父组件,test-item所包含的页面就是子组件,我想要向子组件传一些数值,可以这么写:

test.html:
<test-item [item]='content'></test-item>

item对应的是子组件用来接收数据的标签名,content是父组件向子组件传递的数据的标签名。

我们先在父组件中定义数据:

test.ts:

public content:any=1;

然后在子组件中使用@Input来接收:

test-item.component.ts:

@Input() item;   //item对应的就是在父组件中定义的标签名

//在ngOnChanges()方法里打印一下传进来的数值
ngOnChanges(){
	console.log(this.item)	
}

猜你喜欢

转载自blog.csdn.net/Ariel_201311/article/details/85113086
今日推荐