Angular 6/7, ngIf within ngFor

Asked by At

I am trying to display a set of data in angular. the data is in key value form . I am using *ngFor for iteration. problem is the value part is not uniform in all records. In some records, it is a string, in some records it is an array. So in those cases it is showing [Object object] in my page.

How I can iterate thru this inner array within value field, with *ngIf, that is my question.

part of code

<div class="row" *ngFor='let item of model'>
<div class="col-md-4">{{item.key}}</div>
<div class="col-md-8 " data-toggle="collapse" >{{item.value}}</div>
</div>

screen shot I want to know how to use another *ngFor within *ngIf, and what condition should the *ngIf should have.

3 Answers

1
xyz On

Have a function in your component which checks the value and tells whether it is a string or an Array.

checkValue(val) {
    return val instanceof Array;
}

<div class="row" *ngFor='let item of model'>
    <div class="col-md-4">{{item.key}}</div>
    <ng-container *ngIf="checkValue(item.value) else stringValue">
        <span class="col-md-8 " *ngFor='let subItem of item.value' data-toggle="collapse" >{{subItem}}</span>
    </ng-container>
</div>

<ng-template #stringValue>
   <div class="col-md-8 " data-toggle="collapse" >{{item.value}}</div>
</ng-template?
0
Robin Webb On

Something along these lines:

app.component.ts

.
.
.
 model = [
    {
      key: 'ContextNameSpaces',
      value: [{ a: 1, b: 2 }, { a: 3, b: 4 }]
    },
    {
      key: 'ContextNameSpaces',
      value: 1
    }
  ];

  isObject(val) {
    return typeof val === 'object';
  }

.
.
.

app.component.html

<div *ngFor="let item of model">
  {{item.key}}
  <ng-container *ngIf="isObject(item.value); else elseTemplate">
    <span *ngFor="let j of item.value">
      {{j.a}}
    </span>
  </ng-container>
  <ng-template #elseTemplate>
    {{item.value}}
  </ng-template>
</div>
0
Community On

you can try these:

Objects:

object = [
{
  "id": 1,
  "test": "test1",
  "name": ["abc", "pqr"]

},
{
  "id": 2,
  "test": "test2",
  "name": ["abc2", "pqr2"]

},
{
  "id": 3,
  "test": "test3",
  "name": ["abc3", "pqr3"]

},
{
  "id": 4,
  "test": "test4",
  "name": ["abc4", "pqr4"]
}];

For code :

ngOnInit() {
  for (let item of this.object) {
    for (let i in item) {
      if (typeof (item[i]) === 'object') {
        item[i].forEach((e: any) => {
          console.log("runseprate", e)
        });
      }
    }
  }
}