Reputation: 1145
What is the best approach to access public property from a function?
I have a scenario where when a function is executed, it should update a public property which is an object / array.
Below is my code:
TS file
formName = "support";
formTemplate = {
"types": [
"text",
"file",
"number",
"email"
],
"support": {
"description": "This will generate form for support request",
"fields": [
{
"name": "title",
"element": "input",
"type": "text",
"label": "Title",
"placeHolder": "Provide Short Discription",
"classes": "form-control",
"value": ""
},
{
"name": "description",
"element": "input",
"type": "text",
"label": "Description",
"placeHolder": "Provide Discription",
"classes": "form-control",
"value": ""
},
{
"name": "email",
"element": "input",
"type": "text",
"label": "Email",
"placeHolder": "Provide email addresses",
"classes": "form-control",
"value": ""
},
{
"name": "attachment",
"element": "file-picker",
"type": "file",
"label": "Attachment",
"placeHolder": "Insert Attachment",
"classes": "form-control",
"value": "test"
}
]
}
};
public processForm(data) {
this.formTemplate.support.fields.forEach(function (item, i) {
if (item.element === 'file-picker') {
// THIS DOESN'T WORK. NEED TO ACCESS formTemplate and update value for a property
console.log(this.formTemplate.support.fields[i].value);
}
});
}
So when processForm
is executed from view on click, it should be able to access formTemplate
object. Since this
is local with in the function, need help on accessing formTemplate
which is outside function scope.
Any help is really appreciated. :)
Upvotes: 0
Views: 97
Reputation: 3622
Change your function()
to arrow functions =>
, as they preserve the scope in which they're declared, and therefore this
refers to the class instead of the function.
public processForm(data) {
this.formTemplate.support.fields.forEach((item, i) => {
if (item.element === 'file-picker') {
console.log(this.formTemplate.support.fields[i].value);
}
});
}
Upvotes: 1