Reputation: 982
I want to build an array having this format:
x = [
{'projectName': 'a', 'serialNo': 1},
{'projectName': 'b', 'serialNo': 2},
{'projectName': 'c', 'serialNo': 3},
]
using values passed from a form
onSubmit(form: NgForm) {
let x = []
x.push({
projectName: form.value.projectName,
serialNo: form.value.serialNo,
})
console.log(x) // -> this will always give me the value I just inserted
// form.value.project = JSON.stringify(x)
// putObj(form.value).subscribe((res) => { });
}
Then I send form.value in backend and the field project
is modified. My problem is that everytime I push values into x
, the previous value overrides.
Which seems to be the problem? If my code is unclear, I can explain or give more snippets.
EDIT: thank you very much! It worked, I declared x
inside component.
Upvotes: 0
Views: 1426
Reputation: 416
let x = [] //declare outside
onSubmit(form: NgForm) {
x.push({
projectName: form.value.projectName,
serialNo: form.value.serialNo,
})
}
Upvotes: 3
Reputation: 1693
remove the
let x = []
you can define your array with initial elements within ur onInit method in your component, such as:
type x = Array<{projectName: string, serialNo: number}>;
ngOnInit() {
this.x = [
{'projectName': 'a', 'serialNo': 1},
{'projectName': 'b', 'serialNo': 2},
{'projectName': 'c', 'serialNo': 3},
]
}
onSubmit(form: NgForm) {
this.x.push({
projectName: form.value.projectName,
serialNo: form.value.serialNo,
})
}
Upvotes: 1
Reputation: 61
Yeap, move your let x = [] outside of function. Not sure what you are planning to do, it might need to be a global variable. Every time you enter the function you set x to be an empty array.
Upvotes: 1
Reputation: 1016
not tested, but should work in theory:
// ...
private x: {'projectName': string, 'serialNo':number}[] = [];
// ...
onSubmit(form: NgForm) {
this.x.push({
projectName: form.value.projectName,
serialNo: form.value.serialNo,
});
console.log(this.x)
}
// ...
Upvotes: 1