#name 和 [(ngModel)]="name" 之间有什么区别?在 Angular2 表单输入中? [英] What is the difference between the #name and [(ngModel)]="name" in Angular2 Form input?

查看:31
本文介绍了#name 和 [(ngModel)]="name" 之间有什么区别?在 Angular2 表单输入中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,有些教程使用 # 来获取输入,而有些则使用 [(ngModel)].两者的有效区别是什么?

I am a little bit confused, for some tutorial use # to get the input, while some use the [(ngModel)]. What is the effective difference between the two?

推荐答案

#xxx

#xxx 允许您获取元素引用.

#xxx allows you to get an element reference.

<input #inp (change)="foo = inp.value">

侦听更改事件并调用 onChange() 并传递输入 value 属性

listenes to the change event and calls onChange() and passes the inputs value property

对于双向绑定,您还需要

For two-way binding you also need

<input #inp (change)="foo = inp.value)" [value]="foo = $event">

NgModel

<input [(ngModel)]="foo">

使用 NgModel 指令,允许将 DOM 输入元素和自定义组件集成到 Angular 表单功能中.它也可以在没有表格的情况下使用.NgModel 是对各种元素和组件的抽象,而上述 (#inp) 示例仅适用于具有 value 属性的输入元素并发出一个 change 事件.

uses the NgModel directive that allows to integrate DOM input elements and custom components into Angular form functionality. It can also be used without a form. NgModel is an abstraction over all kinds of elements and components, while above (#inp) example only works for input elements that have a value property and emit a change event.

[(ngModel)]="foo"

[ngModel]="foo" (ngModelChange)="foo = $event"

这表明它用于双向绑定.

which shows it is for two-way binding.

提示

#xxx 返回一个组件或指令实例,如果该元素不是一个普通的 DOM 元素而是一个 Angular 组件或应用了一个 Angular 指令.

#xxx returns a component or directive instance, if the element is not a plain DOM element but an Angular component or has an Angular directive applied.

这篇关于#name 和 [(ngModel)]="name" 之间有什么区别?在 Angular2 表单输入中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆