Reputation: 87
I am new to angular. I was trying to clone a set of elements which is working fine but I am not able to get the latest value of the new cloned element when I console it or in the view.
It might be because of a variable called temp
which is getting the cloned values. How to get the respective fields values in the console like
example=[{
exp1="aaa",
exp2="bbb",
exp3="tea"
},{
exp1="ddd",
exp2="eee",
exp3="mango"
}]
?
Please refer the below link for the working copy of the code: https://stackblitz.com/edit/angular-gvwv4g-h2sxnd
Upvotes: 1
Views: 35
Reputation: 156
You can use it this way
this.example.push(JSON.parse(JSON.stringify(this.temp)));
Please refer the below example https://stackblitz.com/edit/angular-gvwv4g-effowp
Upvotes: 1
Reputation: 5709
You need to copy your form filled values into a new object, then pushing this new object into your array, then you can reset your object value, so the new added line will be empty.
I have edited your input-overview-example.ts
as follow
import { Component , OnInit} from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
/**
* @title Basic Inputs
*/
@Component({
selector: 'input-overview-example',
styleUrls: ['input-overview-example.css'],
templateUrl: 'input-overview-example.html',
})
export class InputOverviewExample implements OnInit {
// test Start
foods=["mango","tea","apple"]
example= [ ];
temp: any;
//test ends
ngOnInit() {
this.initTemp();
this.example.push(this.temp);
}
testAdd(){
console.log(this.temp)
console.log(JSON.stringify(this.example)+"-------");
this.initTemp();
this.example.push({
exp1: this.temp.exp1,
exp2: this.temp.exp2,
exp3: this.temp.exp3,
});
}
initTemp() {
this.temp = {
exp1:"",
exp2:"",
exp3:""
}
}
}
Upvotes: 0