barteloma
barteloma

Reputation: 6845

Using Angular component by json data

I have a lot of card component they are different type. I am getting data of card list from a json array.

[ 
   {id: 1, type: "flower"}, 
   {id: 2, type: "tree"}, 
   {id: 3, type: "animal"}
]

And I have created Angular components of these types:

<flower></flower>
<tree></tree>
<animal></animal>

So I want to add these as dynamically in my app.componnet.html template.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  data: any;

  ngOnInit(){
    this.data = [ 
       {id: 1, type: "flower" }, 
       {id: 2, type: "tree" }, 
       {id: 3, type: "animal" }
    ];
  }
}

my json data comes from server.

Upvotes: 0

Views: 401

Answers (3)

Yash Rami
Yash Rami

Reputation: 2327

you can simply try *ngIf like this.

TS

jsonData = [ 
   {id: 1, type: "flower"}, 
   {id: 2, type: "tree"}, 
   {id: 3, type: "animal"}
];

HTML

<div *ngFor="let data of jsonData; let i = index">
   <flower *ngIf="data.type == flower"></flower>
   <tree *ngIf="data.type == tree"></tree>
    <animal *ngIf="data.type == animal"></animal>
</div>

Upvotes: 1

Askirkela
Askirkela

Reputation: 1209

You could use ngSwitch.

<div *ngFor="let d of data">
  <ng-container [ngSwitch]="d.type">
    <tree *ngSwitchCase="'tree'"></tree>
    <flower *ngSwitchCase="'flower'"></flower>
    <animal *ngSwitchCase="'animal'"></animal>
  </ng-container>
</div>

Upvotes: 0

riorudo
riorudo

Reputation: 1227

Try NgSwitch like:

<container-element [ngSwitch]="type">
  <some-element *ngSwitchCase="flower">...</some-element>
  <some-element *ngSwitchCase="tree">...</some-element>
  <some-element *ngSwitchCase="animal">...</some-element>
</container-element>

Upvotes: 1

Related Questions