Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在HTML中将变量作为参数传递_Html_Angular_Typescript - Fatal编程技术网

在HTML中将变量作为参数传递

在HTML中将变量作为参数传递,html,angular,typescript,Html,Angular,Typescript,我正在尝试调用一个函数,该函数会使单击的字段为空 如果我写(focus)=“this.element.task=null”,它会工作,但是如果我写(focus)=“resetFields(this.element.task)”有办法实现吗 重置字段方法: resetFields(elm) { elm = NULL; this.submitted = false; } Stackblitz上的示例:尝试(焦点)而不是onfocus此: <input [(ngModel)]=

我正在尝试调用一个函数,该函数会使单击的字段为空

如果我写
(focus)=“this.element.task=null”
,它会工作,但是如果我写
(focus)=“resetFields(this.element.task)”
有办法实现吗

重置字段方法:

resetFields(elm) {
    elm = NULL;
    this.submitted = false;
}
Stackblitz上的示例:

尝试
(焦点)
而不是
onfocus
此:

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


由于您通过
[(ngModel)]
绑定到
名称
,因此在组件中更改
名称
也会更改您的模板。

如果您使用的是反应式表单

this.form.reset(); // it will reset all data to blank 
如果您使用的是ngModel,则

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

resetData(){
   this.form = {};
}

重置数据(){
this.form={};
}

您正在通过ngModel将数据绑定到组件中名为
name
的变量,然后将同一变量作为参数从模板/UI传递回组件,并传递给方法
重置字段(名称:any)

这就是为什么在修改ngModel数据绑定到的原始副本时修改组件变量会起作用

resetFields() {
    this.name = null;
  }

Javascript是按值传递的,只有对于对象,该值才是对该对象的引用。看

因此,原始问题的答案是否定的。您不能修改函数内部的内容,也不能看到函数外部的结果,因为更改在当前函数范围内可见。您只能将对象发送到该函数并修改该对象

resetFields(elm) {
    elm = NULL;  //won't work, will only set reference to elm to null inside resetFields function scope
    elm.someProperty = null; //will work
}
但是,您可以这样做:

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

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

更新。

您能创建一个复制此问题的StackBlitz示例吗?我想您应该尝试
(焦点)=“resetFields(element.task)”
当您尝试调用它时发生了什么?控制台上正在生成哪些错误消息?我立即注意到您说过,
resetFields
是一种方法。。。但对我来说,它看起来像一个函数。@mohamedialrachid是真的,你的stackblitz说的
onfocus=…
应该是
(focus)=…
,在你的stackblitz链接中,它使用
(focus)而不是
(onfocus)
resetFields(elm) {
    elm = NULL;  //won't work, will only set reference to elm to null inside resetFields function scope
    elm.someProperty = null; //will work
}
resetFields(elm, property) {
    elm[property] = null;
}

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