2

I'm trying to call a function which nulls the field clicked,

if I write (focus)="this.element.task=null" , it works but if I do (focus)="resetFields(this.element.task)" is there a way to achieve this?

resetFields method:

resetFields(elm) {
    elm = NULL;
    this.submitted = false;
}

Sample on Stackblitz: http://stackblitz.com/edit/angular-nvgtec

prevox
  • 536
  • 3
  • 11
  • 21

4 Answers4

1

Javascript is pass by value, only for objects the value is the reference to that object. See this question.

So the answer to your original question is no. You cannot modify something inside the function and see the results outside the function as the changes are visible in current function scope. You can only send object to that function and modify that object.

resetFields(elm) {
    elm = NULL;  //won't work, will only set reference to elm to null inside resetFields function scope
    elm.someProperty = null; //will work
}

You could however do it like this:

resetFields(elm, property) {
    elm[property] = null;
}

(focus)="resetFields(this.element, 'task')"

Updated stackblitz demo.

Ludevik
  • 6,954
  • 1
  • 41
  • 59
0

Try (focus) instead of onfocus this:

<input [(ngModel)]="name" (focus)="resetFields()">

Since you're binding to name via [(ngModel)], changing name in your Component will also change your template.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
0

If you are using reactive forms then ...

this.form.reset(); // it will reset all data to blank 

If you are using ngModel then

<input name="name" [(ngModel)]="form.name" (focus)="resetData()">

resetData(){
   this.form = {};
}
Sachin Shah
  • 4,503
  • 3
  • 23
  • 50
0

You are data binding to a variable in your component called name via ngModel, and then passing the same variable back to the component from the template/UI as an argument to the method resetFields(name: any)

<input [(ngModel)]="name" (focus)="resetFields(name)">

Because you are passing a "copy" of name from the teamplate/UI as an argument to your method resetFields, it is in fact modifying that copy of name, but it does not alter the original that ngModel is using... and because you never do anything with the argument after you modify it... it does not work.

 resetFields(name: any) {
    console.log(name);
    name = null;
    console.log(name);
  }

This is why modifying the component variable works as you are modifiying the original copy that ngModel is data binding to.

resetFields() {
    this.name = null;
  }
Marshal
  • 10,499
  • 2
  • 34
  • 53