RenegadeAndy
RenegadeAndy

Reputation: 5690

Angular2 passing a JSON object to the constructor of a component

I have the following scenario where my first component config.editor.component does a lot of processing and creates a variety of different JSON objects.

I am happy with this approach. The template for this component then renders another component - api.entry.component using a *ngFor loop. How can I pass a JSON object which I created in my config.editor.component.ts into the constructor of my api.entry.component?

My current template looks like this :

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

The object I want to pass into the constructor is actually 'api' seen above. This object is created in the config.editor.component.ts file as per this code which executes all as I would expect and assigns a JSON array to the apis variable :

 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;
      });
  }

All I really want is to be able to access the specific api from my template loop in the constructor of my api.entry.component.ts:

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!
  }

}

I feel this must be quite simple but I am struggling to see how it works! Please help me understand how I can pass my JSON object in the *ngFor loop into the constructor of the component the template is building.

Upvotes: 0

Views: 1962

Answers (1)

Carlos Mermingas
Carlos Mermingas

Reputation: 3892

Define api using the Input decorator in your ct-api-entry component:

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() {}
}

And then you pass it in the template:

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

Upvotes: 2

Related Questions