I have an Angular 2 app where I want to list off all of the locations in my data (that I pull in with my service).
Inside my parent I plan to list them off with an *ngFor:
<ul *ngFor="let location in myservice.locations"></ul>
Firstly, is this possible? The component will repeat once for each location, and look the same other than the data.
I'm just not sure where to start. If my service received 4 locations objects each with name, and date data, How can I go about this?
I'm thinking my location (child) component will look something like this?
...
export class locationComponent implements OnInit{
constructor(private _myserviceService: MyserviceService) {
}
obj;
ngOnInit(){
var locationname = ;
var locationdate = ;
let observable = this._myserviceService.getLocations();
observable.subscribe(data => {
this.obj = data
})}
The html will be something like:
{{location.locationname}}
{{location.locationdate}}
Mainly my question is, how do I make sure I construct my location component so that it can be reused with multiple data objects and I can loop through them?
Thanks!! Let me know if I can clarify.
Take a look at this . I think this is what you are looking for.
I am passing
[{
id: 'location 1'
},{
id: 'location 2'
}]
using *ngFor
loop to the child component where each object can be rendered as per the component.
First, the data received form the endpoint will be stored in this.obj ( code : this.obj = data ), then in your html you can
<ul *ngFor="let location in obj">
<li>{{location.locationname}}</li>
<li>{{location.locationdate}}</li>
</ul>
that will show two lines for each location
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.