[英]How can I pass the objects from Parent component to the Child component in Angular 2?
Here HousingAppComponent is my parent class and I want to pass this view object to my child component CoursesComponent so that I can display the members from the view object in the courses.html page. 这里HousingAppComponent是我的父类,我想将此视图对象传递给我的子组件CoursesComponent,以便可以在courses.html页面中显示该视图对象的成员。
export class HousingAppComponent {
views: Object[] = [
{
name: "Courses",
description: "Show the courses",
icon: "assignment"
},
{
name: "Users",
description: "Check your Progress",
icon: "account_circle"
}
];
The easiest way to pass data to a child component is with property binding . 将数据传递给子组件的最简单方法是使用属性绑定 。 The view of HousingAppComponent will pass the
views
property to CoursesComponent. HousingAppComponent的视图会将
views
属性传递给CoursesComponent。 See the following: 请参阅以下内容:
housing-app.component.html: 住房app.component.html:
<courses [someData]="views"></courses>
courses.component.ts: courses.component.ts:
import {Component, Input} from '@angular/core';
@Component({
...
})
export class CoursesComponent {
@Input() someData: any;
}
The [someData]="views"
notation means that you are setting the CoursesComponent.someData
property with an expression that is evaluated between the quotation marks. [someData]="views"
表示您正在设置CoursesComponent.someData
属性,并使用在引号之间进行计算的表达式。 It evaluates "views"
as the HousingAppComponent.views
property. 它将
"views"
评估为HousingAppComponent.views
属性。
You can use @viewchild
annotations to have a reference of child in parent and use that to pass any data. 您可以使用
@viewchild
批注在parent中具有child的引用,并使用该引用传递任何数据。 Please not the child will be available only after ngAfterViewInit lifecycle event. 请不要让孩子只有在ngAfterViewInit生命周期事件之后才可用。
@Viewchild(CourseComponent) cc:CourseComponent cc.Course = data
You can also pass data via angular data binding in HTML. 您还可以通过HTML中的角度数据绑定传递数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.