What's the difference between ref- prefix and

2019-05-09 13:38发布

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 ?

3条回答
混吃等死
2楼-- · 2019-05-09 14:01

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

my html page

Output

output

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

查看更多
Melony?
3楼-- · 2019-05-09 14:04

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.

查看更多
成全新的幸福
4楼-- · 2019-05-09 14:05

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

查看更多
登录 后发表回答