iv444
iv444

Reputation: 985

How to show different JSON data on a component in Angular4?

I have a reusable component, this component fetches a data from a JSON file. However, I'd like to show different data (from different JSON path) when this component is used on other components as a subcomponent.

Example, I have a Banana component

@UxComponent({
  selector: "[banana]",
  host: {
    class: "bananaClass"
  }
})

export class BananaCmp extends BaseMolecule {
public name = "Banana";
public description = "Banana is awesome";
public data: any;

public permittedParams: any = {
  // Insert the permitted config parameters (remove this line when done)
};

public ngOnInit () {
  this.jsonService.loadData("BananaData").then(
    (data: any) => this.data = data
  );
}

Then imagine I'd like to use this Banana component inside Fruits component.

export class FruitsCmp extends BaseMolecule {
public name = "Fruits";
public description = Fruits are healthy!";
public data: any;

public permittedParams = {
  // Insert the permitted config parameters (remove this line when done)
};  

public config = {
  // Insert the default config (remove this line when done)
};

public ngOnInit () {
  // Maybe something like this, but I need to make sure only FruitsData.json is being fetched. Not both BananaData & FruitsData
  // this.jsonService.loadData("FruitsData").then(
  //  (data: any) => this.data = data
  //)
};

How to do this properly?

Upvotes: 0

Views: 138

Answers (3)

brijmcq
brijmcq

Reputation: 3418

To make your BananaCmp truly reusable, the component should have no idea where the data is coming from. But in your case, you probably just want an @Input() then override the default data something like this

export class BananaCmp extends BaseMolecule {
public name = "Banana";
public description = "Banana is awesome";
public data: any;
@Input inputData:any;

public ngOnInit () {
        if(inputData){
          this.data = inputData;
         }else{
         this.jsonService.loadData("BananaData").then(
           (data: any) => this.data = data
        );
   }
//...
}

Or just remove the jsonService part completely.

Then you can use the component in your FruitCmp like this

<banana [inputData]="data"> </banana>

Upvotes: 1

Sasxa
Sasxa

Reputation: 41254

You can make data an input property, and pass value from parent component:

// component.html
<div banana [data]="jsonService.loadData('BananaData') |async" />
<div fruits [data]="jsonService.loadData('FruitsData') |async" />

// component.ts
@Input() data;

Upvotes: 0

Vega
Vega

Reputation: 28708

Set an @Input on the reusable component. Then set an attribute on that component view selectors which will take the values from the parent component. That value should contain JSON file names.

Upvotes: 0

Related Questions