Adnan Abdul Khaliq
Adnan Abdul Khaliq

Reputation: 495

Angular 4- *ngFor not functioning on Array of Objects

I have some problems in looping at the html side using *ngFor on the data received from the REST service below is what i am doing:

  getQuestionaire(type: String) {
    const url = `${this.questionaireTypeUrl}/${type}`;
    return this.http.get(url).map(
      (response: Response) => {const questioniares: any[] = response.json();
        return questioniares;
      }
    );
  }

Here i call the function in one of the app.component.ts:

  ngOnInit() {
    this.route.params
    .subscribe(
      (params: Params) => {
        this.quesType = params['type'];
        this.questionaireService.getQuestionaire(this.quesType).subscribe(
          (questionaires: any[]) => {
            this.questionaire = questionaires;
            console.log(this.questionaire);
          }
        );
      }
    );
  }

Here i am looping using *ngFor on the html side and creating a table dynamically

<table class="table ">
      <thead>
        <tr>
          <th class="active">QUESTIONAIRE NAME</th>
          <th class="active">LEVEL</th>
          <th class="active">LAST MODIFIED</th>
          <th class="active">PUBLISHED BY</th>
          <th class="active">VALIDITY DATE</th>
        </tr>
      </thead>
      <tbody *ngFor="let questionaireEl of questionaire">
        <tr>
          <td>{{ questioniareEl.nameQuestionaire }}</td>
          <td>{{ questionaireEl.levelQuestionaire }}</td>
          <td>{{ questionaireEl.lastUser }}</td>
          <td>{{ questionaireEl.publishingUser }}</td>
         </tr>
      </tbody>
 </table>

Problem: The console logs the data i am looping on it consists of an array of objects and i can't figure out how could i access the elements i need to display please help!!

enter image description here

Upvotes: 0

Views: 1184

Answers (2)

micronyks
micronyks

Reputation: 55443

Here ?. comes to rescue

generally when async call happens, you exactly don't know when would result come/arrive to the template. But other hand, template would get parsed to HTML and it would want to display the data that have not yet arrived from the async call.
So until data comes back, ?. operator would wait (& would not throw any template error).
once data arrives, ?. operator allows to print the arrived data.

eg.

{{questioniareEl?.nameQuestionaire}}

Upvotes: 1

Mixalloff
Mixalloff

Reputation: 837

You need to use async pipe <tr *ngFor="let questionaireEl of questionaire | async">...

Or you can write

<td>{{ questioniareEl?.nameQuestionaire }}</td>
<td>{{ questionaireEl?.levelQuestionaire }}</td>
...

to avoid that error

Upvotes: 1

Related Questions