Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use ViewChild and NgModel, how are they different?

Tags:

angular

I am getting a little confused about ViewChild and NgModel. Can anyone give me definitive answer of when to use Viewchild and ngModel? I understand both will point to a particular element and you can use those objects to get the current value of element.

like image 903
Shinya Koizumi Avatar asked Mar 26 '19 18:03

Shinya Koizumi


2 Answers

NgModel

NgModel is a way of two way data binding and can be used within your template and controller and if the value is changed in one it will reflect withing the other. A very common use would be with an input box looking, which could look like so.

<div>
    <input class="input-box" ([NgModel])]="myValue">
</div>

Which would sit in the controller as.

public myValue: string = 'hello;'

If this was either by the user from within the input box the variable myValue would change reflectively. If in the template you change the value like so. this.myValue = 'goodbye'' this would change within the text box.

NgModel documentation

ViewChild

The viewchild can get be used to get reference of template elements, so you can see all the associated attributes. A common example would be if there were to be a custom component in a template a ViewChild could be used to pull values out of that component when needed. Looking roughly like so.

<my-custom-component #reference></my-custom-component>

Then in your controller you could define.

@ViewChild('reference')public myComponent; // type being the class of the child / element.

This would then allow you to gain access to everything inside the child component. I think why you are drawing a comparison is that you could do this with an input box and extract its value.

ViewChild documentation

Both are very useful tools with different applications. For generic two way data binding stick with NgModel, for obtaining reference to template elements / components I would stick with ViewChild.

like image 65
Dince12 Avatar answered Oct 20 '22 02:10

Dince12


NgModel is used for inputs and is used within forms whereas a Viewchild can be used to point to a component/directive you have on your page.

NgModel will give you values for a given form field

ViewChild will allow you to access all public properties (values) and methods of the component you are pointing too.

like image 35
Derrick Awuah Avatar answered Oct 20 '22 02:10

Derrick Awuah