What's the difference between ref- prefix and # in Template reference variable (Angular 2)

亡梦爱人 提交于 2019-12-22 08:40:12

问题


I want to understand the difference between template reference variable notations as mentioned below in the input text boxes.

<input type="text" name='name' #name [(ngModel)]='model'>
<input type="text" name='name' ref-name [(ngModel)]='model'>

What's the difference between using #name and ref-name.
Does the scope of the variable changes on using ref-name ?
Can anybody please suggest the best practice and reason ?


回答1:


They are two different syntaxes for literally exactly the same thing.

You can think of it this way: some people (and editors) don't like the new '#variable' syntax, so Angular provides an option to use the exact same functionality using a more 'palatable' syntax.




回答2:


Template reference variable is a variable using which we can access DOM properties.

Using template reference variable we access the values of DOM element properties. Template reference variable is declared using # and ref- as a prefix, for example, #item and ref-item.

Example : template reference variable using input textbox

<input type="text" #name placeholder="Enter your name" />

Here #name is template reference variable, to fetch DOM properties we do follow

name.placeholder it give "placeholder of our textbox" if we have specified.

name.value it give us to "value" of our textbox.

name.type it give us to "type" of our textbox.

Here is my example which I created.

HTML Page

Output

you can do same thing with ref-name reference variable.




回答3:


Template reference variable is a variable using which we can access DOM properties. A reference variable refers to its attached the element, component or directive. It can be accessed anywhere in the entire template.

<input type="text" name='name' #name [(ngModel)]='model'>

#name declares a name variable on an element. The reference #... now always means ref-. Use # or a ref- outside of *ngFor. And you can refer following URL:http://www.concretepage.com/angular-2/angular-2-template-reference-variable-example



来源:https://stackoverflow.com/questions/43592556/whats-the-difference-between-ref-prefix-and-in-template-reference-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!