比如我有一个父组件,而在父组件中有多个相同的组件,比如父组件使用了ngFor循环,而在ngFor下面有一个子组件,这样当循环出来后就有很多个子组件了。那么我们要如何才能获得这几个子组件中的相应数据集合呢?之前我到segmentfault进行了提问,但是并没有人为我回答,终于在对官方文档阅读以及google了很多后,终于找到答案了。下面就让我们去解开angular2的面纱吧。
在angular中,我们需要从相同子组件中获取相关字段,我们可以直接使用@ViewChildren,如果你E文较好,那么我们把这个单词拆开来理解@ViewChildren,View Children,view是视图或者显示,children则是孩子或者子类,简单的说就是获取子组件的相关集合。
我使用它做了一个简单的demo,地址是:http://www.egtch.com/demo/angular/
在实例中显示如下图:
首先我们直接点击“点此获得点“赞”的数据集合”即可显示相关数据。
另外我们可以通过点击每一个电影下面的+号来查看所获得的数据。
相关源码:
子组件ViewChildrenCom.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'vc',
templateUrl: './ViewChildrenCom.html',
styleUrls: ['./ViewChildrenCom.css']
})
export class iViewChildren {
count=0;
constructor(){}
addCount(){
this.count++
}
}
ViewChildrenCom.html
赞 {{count}} 次+
ViewChildrenCom.css
.l {
float: left;
font-size: 12px;
background: #ccc;
color: #fff;
padding: 2px;
}
.r {
float: right;
width: 50px;
font-size: 12px;
background: #4169e1;
color: #fff;
padding: 2px;
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.i {
float: right;
font-size: 12px;
background: #a52a2a;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
color: #fff;
padding: 2px 6px;
}
下面我们来看父组件的相关代码
ViewChildren.ts
import { Component, QueryList, ViewChildren } from '@angular/core';
import {Http} from '@angular/http';
import {iViewChildren} from '../ViewChildrenCom/ViewChildrenCom';
@Component({
selector: 'ViewChildren',
templateUrl: './ViewChildren.html',
styleUrls: ['./ViewChildren.css']
})
export class MyViewChildren {
title = '@ViewChildren获取子组件传递的数据集合';
url = 'assets/data.json';
data = '';
count:any;
constructor(public http:Http){
http.get(this.url).subscribe(res=> this.data = res.json());
}
//获得count组件的数字集合
@ViewChildren(iViewChildren) listCount: QueryList
getCount(){
this.count = this.listCount.toArray();
console.log(this.count);
// alert('目前获得的内容:'+this.count+' 可以直接查看浏览器调试中获得的这几条数据');
return this.count
}
}
ViewChildren.html
{{title}}
-
{{m.name}}{{m.start}}分
ViewChildren.css
.clearfix {
content: '';
height: 0;
display: block;
clear: both;
overflow: hidden;
}
.myTest {
width: 80%;
margin: 0 auto;
}
.myTest .inner {
width: 100%;
padding-top: 10px;
}
.myTest .inner .bt {
background: #00008b;
color: #fff;
border: none;
border-radius: 5px;
padding: 3px 6px;
}
.myTest .inner .ct {
color: #a52a2a;
font-size: 12px;
padding: 10px;
}
.myTest .movie-list {
width: 120px;
height: auto;
margin: 10px;
padding: 5px;
display: inline-block;
background: #eee;
border-radius: 5px;
}
.myTest .movie-list:hover {
box-shadow: 0 1px 10px #333;
}
.myTest .movie-list .image {
width: 100%;
}
.myTest .movie-list .image>img {
width: 120px;
height: 160px;
}
.myTest .movie-list .name,
.myTest .movie-list .start {
display: block;
width: 100%;
font-size: 16px;
text-align: center;
padding: 2px 0;
}
.myTest .movie-list .name {
border-bottom: 1px #ddd solid;
}
.myTest .movie-list .start .l {
float: left;
font-size: 12px;
background: #ccc;
color: #fff;
padding: 2px;
}