Differences between value and ngValue in Angular 5

a 夏天 提交于 2019-11-26 16:42:59

问题


Today I realized about an unexpected (for me) behaviour of the reactive forms in Angular 5. The server was receiving from the app an string with the value "null" instead of the null value, whichh is what I wanted.

I did the following test:

https://stackblitz.com/edit/angular-rjrspr?file=app%2Fapp.component.html

As you can see in the picture below, if I use [value]="null" in the select, the field is getting "null" (string literal) as value. However, if I use [ngValue]="null" it gets the expected null value.

I thought that using value was intended for reactive forms, while ngValue was for template driven forms. I'd like to know if it's safe to use both in my forms (I always use reactive forms) and if there's any explanation for the different behaviour.

Thanks!


回答1:


Its ok to use valueor ngValue.

The only difference between two is that value is always string, where in ngValue you can pass object




回答2:


const items = ["foo", "bar", "baz"]

<option *ngFor="let item of items" [value]="item">
    {{item}}
</option>

using [value] when one of the options is selected the value will be foo, bar, baz

<option *ngFor="let item of items" [ngValue]="item">
    {{item}}
</option>

using [ngValue] when one of the options is selected the value will be 0: foo, 1: bar, 2: baz




回答3:


there is no much diffrence between value or ngValue.

The only difference is that,

when you have String as input then use value and

when Object as input then use ngValue.




回答4:


value must be string but ngValue- is whatever you want. Value will not bind to selectlist if value type is int not string.



来源:https://stackoverflow.com/questions/49918687/differences-between-value-and-ngvalue-in-angular-5

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