2017-03-08 80 views
0

我正在使用Angular 2Ionic 2我想从父组件获取属性。访问Angular 2中组件的儿童属性

所以我的父母composent是一个名为“ServicesPage”类,而我的孩子组件被命名为“AddonCell”。

ServicesPage.html

<ion-content> 
    <ul *ngIf='savedAddons'> 
    <addon-cell [type]="addon" *ngFor="let addon of savedAddons"></addon-cell> 
    </ul> 
</ion-content> 

ServicesPage.ts

@Component({ 
    selector: 'page-services', 
    templateUrl: 'services.html' 
}) 

export class ServicesPage { 
    // [...] 
    refreshInstalledAddons() : void { 
     console.log("[+] Getting properties of all addon-cell ..."); 
     // I would like a for loop here to get all AddonCell objects 
     // and access properties like : myAddon.myVar 
    } 
} 

AddonCell.ts

@Component({ 
    selector: 'addon-cell', 
    template: `<div #target></div>` 
}) 
export class AddonCell { 
    @ViewChild('target', {read: ViewContainerRef}) target; 
    @Input() type; 
    myVar = false; // <---- Trying to get this variable 
    //[...] 
} 

UPDATE

AddonModule

// Angular core component 
import { NgModule } from '@angular/core'; 

import { AddonCell } from './components/system/common/cell.component'; 

// Importing and exporting all addons 
export { MeteoAddon }  from './components/meteo/meteo.addon'; 
import { MeteoAddon }  from './components/meteo/meteo.addon'; 

import { MeteoPagesModule } from './components/meteo/pages/meteo.module'; 

// Creating an array containg addons class names 
// Please note, it's used for further instanciations 
export let classNameArray = ["MeteoAddon"]; 

export let addonsMap = { 
    'MeteoAddon' : MeteoAddon }; 

@NgModule({ 
    declarations: [ 
    AddonCell, 
    MeteoAddon], 
    imports: [ MeteoPagesModule ], // Importing all addon's pages 
    entryComponents: [ MeteoAddon ], 
    exports: [ 
    AddonCell, 
    MeteoAddon] 
}) 

export class AddonModule {} 

注:savedAddons是含阵列串实例名。

所以主要问题是如何获取所有的实例化对象AddonCell以访问属性?

+0

不清楚! Servicepage.ts是指组件或注入服务? – Aravind

+0

这是一个组件 – iDev

+0

我编辑我的问题是更明确 – iDev

回答

0

感谢您的帮助,但我找到了解决方案!

我说我ServicePage.ts这样的:

@ViewChildren('addoncell') components:QueryList<AddonCell>; 
/// [...] 
refreshInstalledAddons() : void { 
    this.components.forEach(function(element) { 
     console.log(element.cmpRef.instance.myVar); 
    }); 
} 

ServicePage.html,我添加了一个标识符与

<addon-cell #addoncell [type]="addon" *ngFor="let addon of savedAddons"></addon-cell> 
0
class ServicesPage { 
    @ViewChild(AddonCell) 
    addonCell: AddonCell; 

    getVar() { 
    // this.addonCell.myVar 
    } 
} 
+0

Thx为您的答复,但我有一个错误消息:“意外的价值'未定义'模块导出'AddonModule'” – iDev

+0

告诉你AddonModule请 –

+0

我编辑我的问题thx ! – iDev