Reputation: 165
I am trying to copy a property in angular (volunteership to x) because I want to edit the property and leave volunteership the way it is. Here is the code from ts:
volunteership;
x ;
constructor(private viewvolunteershipService: Volunteership,
private router: Router) {}
ngOnInit() {
this.viewvolunteershipService.getVolunteership().subscribe(volunteership =>
this.volunteership = volunteership);
console.log("Volunteership", this.volunteership);
this.x = this.volunteership;
}
Here, in HTML I want to call the property x on a ngFor so I can choose a city from it, but it shows me nothing. If I use volunteership instead of x it's working perfectly. How can I copy volunteership to x so I could choose a city from it?
<div class="form-group" >
<label for="city" >City</label>
<select id="city" class="form-group" >
<option value=""></option>
<option *ngFor=" let z of x" >{{z.city}}</option>
</select>
</div>
I've already tried to copy as an array
for (var i = 0, len = this.volunteership.length; i < len; i++) {
this.x[i] = this.volunteerhip[i];
}
I've even tried using Object.assign() method and still nothing.
Upvotes: 3
Views: 59
Reputation: 73357
First of all you need to do the assignment in the callback (subscribe
) as per explained here: How do I return the response from an Observable/http/async call in angular2? but you mention that you only want the changes to reflect in the x
array. As is, all changes will happen to both arrays, as x
has a reference to volunteership
, what you'd probably want to use Object.assign
:
ngOnInit() {
this.viewvolunteershipService.getVolunteership().subscribe(volunteership => {
this.volunteership = volunteership;
this.x = this.volunteership.map(obj => Object.assign({}, obj))
});
}
now x
array will not have a reference to the volunteership
array.
Upvotes: 1