How can I copy an angular property to another?
I am trying to copy a property in angular (volunteering on x) because I want to edit the property and leave the volunteering as 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 name property x on ngFor so I can select a city from it, but that doesn't show me anything. If I use volunteering instead of x, it works great. How can I copy volunteering to x to select a city?
<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 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 even tried using Object.assign () method and still nothing.
source to share
First of all you need to do the assignment in the callback ( subscribe
) as described here: How to return the response from the Observable / http / async call in angular2? , but you indicate that you want the changes to be reflected in the array x
. Like all changes will happen to both arrays, since it x
has a link to volunteership
what you 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 the x
array will not have a reference to the array volunteership
.
source to share