Angular2将JSON对象传递给组件的构造函数

时间:2016-10-28 02:16:34

标签: javascript json angular electron

我有以下场景,我的第一个组件config.editor.component进行了大量处理并创建了各种不同的JSON对象。

我很满意这种方法。然后,此组件的模板使用* ngFor循环呈现另一个组件 - api.entry.component。如何将我在config.editor.component.ts中创建的JSON对象传递到api.entry.component的构造函数中?

我目前的模板如下所示:

<!-- loop and display all api components here -->
<ct-api-entry *ngFor="let api in apis"></ct-api-entry>

我想传递给构造函数的对象实际上是&#39; api&#39;见上文。此对象在config.editor.component.ts文件中根据此代码创建,该代码按照我的预期执行所有操作并将JSON数组分配给apis变量:

 clicked(event){
      ipc.send('open-file-dialog');
      ipc.on('selected-directory', (event, obj) => {
        this.server_description = obj.description;
        this.features = obj.features;
        this.apis = obj.apis;
        this.wola_configs = obj.configs;
        this.connection_factories = obj.connection_factories;
      });
  }

我真正想要的是能够在我的api.entry.component.ts的构造函数中从我的模板循环访问特定的api

import { Component } from '@angular/core';

@Component({
  selector: 'ct-api-entry',
  templateUrl: 'api.entry.component.html',
  styleUrls: ['api.entry.component.css']
})
export class APIEntryComponent {
//I NEED TO PASS THIS CONSTRUCTOR AN SPECIFIC JSON OBJECT FROM APIS IN THE CONFIG-EDITOR MAIN COMPONENT
  constructor() {
 //I WANT TO ACCESS MY JSON API OBJ IN HERE!
  }

}

我觉得这一定很简单,但我很难看到它是如何运作的!请帮助我理解如何将* ngFor循环中的JSON对象传递给模板构建的组件的构造函数。

1 个答案:

答案 0 :(得分:2)

使用api组件中的Input装饰器定义ct-api-entry

import { Component, Input } from '@angular/core';

@Component({
  selector: 'ct-api-entry',
  templateUrl: 'api.entry.component.html',
  styleUrls: ['api.entry.component.css']
})
export class APIEntryComponent {
   @Input() api: any;   
   constructor() {}
}

然后你在模板中传递它:

<ct-api-entry *ngFor="let api of apis" [api]="api"></ct-api-entry>