0

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.

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

2 Comments

Using ngFor loop?
You can wrap the ngSwitch elements with a ngFor. Like the answer of Askirkela
0

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>

1 Comment

Multiple div tags will be added in this stuation. Can I change div with ng-container

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.