I have an hero array that I show it in list by *ngFor and when I Click on one of it element it copied on new variable and new variable go to input by tow way binding . my heroClass:
export class Hero {
id: number;
name: string;
}
my hero-mock list:
import { Hero } from './heroClass';
export const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
My hero component:
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes = HEROES;
selectedHero: Hero;
constructor() { }
ngOnInit() {
}
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
}
heroes.component.html
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
<div *ngIf="selectedHero">
<h2>{{ selectedHero.name | uppercase }} Details</h2>
<div><span>id: </span>{{selectedHero.id}}</div>
<div>
<label>name:
<input [(ngModel)]="selectedHero.name" placeholder="name">
</label>
</div>
</div>
the problem is when i select one hero and show copy of it on text input and change it the hero of list that is selected changing too.
in angularjs 1 I prevent from this issue by using angular.copy() built in method but in angular 2 i have to create new of Hero and attributing propery of selectedHero to main hero:
selectedHero: new Hero();
onSelect(hero: Hero): void {
this.selectedHero.name = hero.name;
this.selectedHero.id= hero.id;
}
is there other way to deep copy in angular 2 without using jquery or js function and above way?
parse() and Stingify() methods. Among the above mentioned three ways, for an object to be deep cloned, JSON. stringify() and JSON. parse() functions are used.
The alternative for deep copying objects having nested objects inside is by using lodash's cloneDeep method. For Angular, you can do it like this: Install lodash with yarn add lodash or npm install lodash .
copy() creates a new object as a deep copy.
This is pretty hacky in my opinion, but it does work.
this.selectedHero = JSON.parse(JSON.stringify(hero));
For Shallow Copy: You can use the spread operator:
this.selectedHero = {...hero};
let {...example} = hero;
Use lodash's cloneDeep
function.
There's nothing in Angular for deep cloning an object because it is not Angular's concern to provide such a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With