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

标签 html angular typescript

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

如果我写 (focus)="this.element.task=null" ,它可以工作,但如果我写 (focus)="resetFields(this.element.task)" 有办法实现吗?

重置字段方法:

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

Stackblitz 上的示例:http://stackblitz.com/edit/angular-nvgtec

最佳答案

Javascript 是按值传递的,仅对于对象,值是对该对象的引用。参见 this question .

所以你原来的问题的答案是否定的。您无法在函数内部修改某些内容并在函数外部查看结果,因为更改在当前函数范围内可见。您只能将对象发送到该函数并修改该对象。

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 demo .

关于html - 在 HTML 中将变量作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174816/

相关文章:

javascript - <a> 点击不工作但 href 是正确的并且工作

javascript - 如何使用javascript在输入开始时放置一个不能删除的字符

Angular 2 Mobile Toolkit --mobile 标志不起作用

angular - Resolver 或 Guard - 更适合使用 ngrx 获取数据

angular - 错误类型错误 : Failed to execute 'append' on 'FormData' : parameter 2 is not of type 'Blob' . Angular 6

typescript - TypeScript 中的双等号 (==)

javascript - 当我将 SVG 内容绘制到 Canvas 时,SVG 被裁剪

html - JSP include 在链接中添加项目名称前缀

html - CSS 文本环绕问题和共同主持人的 HTML 设置

javascript - 在 webpack 中暴露 UIkit