I have a scenario where I make an API call to fetch user profiles, and I want to generate Angular Material Design md-cards dynamically for each profile. The number of profiles retrieved can vary, hence the need for dynamic card creation.
Below is the component file responsible for making the JSONP request and storing the profiles in the profiles
variable:
import {Component, Injectable, OnInit} from '@angular/core';
import {Jsonp} from '@angular/http';
@Component({
selector: 'app-staff',
templateUrl: './staff.component.html',
styleUrls: ['./staff.component.css']
})
@Injectable()
export class StaffComponent implements OnInit {
public searchField: string;
apiUrl = 'this/is/my/api/url';
public results: JSON;
public profiles;
constructor(private jsonp: Jsonp) {
}
ngOnInit() {
}
setSearchField(field: string){ // ignore this method
this.searchField = field;
console.log('Received field: ' + this.searchField);
}
search(term: string) {
const apiUrl = `${this.apiUrl}?search=${term}&rows=10&callback=JSONP_CALLBACK`;
return this.jsonp.request(apiUrl).map(results => { this.results = results.json(); console.log(this.results['profiles'][0]); this.profiles = results['profiles']; return results.json(); });
}
}
This is the template section pertaining to the above component, where I attempt to use *ngFor
to create a list of md-card
:
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-auto">
<ul>
<li *ngFor="let profile of profiles">
<md-card class="example-card">
<md-card-header>
<div md-card-avatar class="example-header-image"></div>
<md-card-title>{{profile.fullName}}</md-card-title>
<md-card-subtitle>Department</md-card-subtitle>
</md-card-header>
<img md-card-image src="../assets/image.png">
<md-card-content>
<p>
This section of the card will contain information about the result being searched for. It could also be
accompanied by additional information such as links.
</p>
</md-card-content>
<md-card-actions>
<button md-button>APPLY</button>
<button md-button>GO TO xyz</button>
</md-card-actions>
</md-card>
</li>
</ul>
</div>
</div>
</div>
The profile data is stored in an array format (assuming a maximum length of 10) with the following structure:
0: {fullName: "Foo Bar", emailAddress: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8ded7d7dad9caf8ded7d7dad9ca96dbd7d5">[email protected]</a>", image: "/profile/image/foobar/foobar.jpg", phoneNumber: "99999999"},
1: {fullName: "Foo Bar1", emailAddress: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcdc4c4c9cad99aebcdc4c4c9cad985c8c4c6">[email protected]</a>", image: "/profile/image/foobar1/foobar1.jpg", phoneNumber: "919999999"}
Despite having confirmed that profiles
is not empty, the md-card
s are not rendering. How do I proceed to dynamically generate cards based on the number of profiles and populate them with values from the profile objects?