1

I am using following to place values in an Input field. Setting values of input fields with Angular 6

<input matInput placeholder = "ProductName" [(ngModel)]="orderLine.productname">

However, sometimes the value maybe null. When placing a question mark ? below, we receive the following error, how does someone place possible blank null value in input, or is not possible?

<input matInput placeholder = "ProductName" [(ngModel)]="orderLine?.productname">

The '?.' operator cannot be used in the assignment at column in [[orderLine?.productname=$event]

  • Could we take a look at how you're declaring orderLine in your ts? Are you utilizing a FormGroup() w/ Form Controls? – dnunez32 Nov 27 '19 at 05:21
  • 1
    hi @dnunez32 we are not using formgroup, I tried it both ways with model member null ? and not null in declaration –  Nov 27 '19 at 05:27

5 Answers5

2

Please split it into two parts as these two are part of ngModel::

[ngModel]="orderLine?.price" (ngModelChange)="orderLine.price = $event"
Sudeep Sagar
  • 253
  • 1
  • 10
  • what if there is no field `(price)` is presented in the orderLine object..? – Ganesh Nov 27 '19 at 05:31
  • whats the difference between Mutsahen answer and yours? both seem good by the way, maybe just different flavors of doing things, –  Nov 27 '19 at 06:17
  • @ganesh045 put if condition to check whether your field exist or not. If your field exist then this will work otherwise it'll skip. Please refer this, you'll find your answer:: https://stackoverflow.com/questions/37111005/how-to-check-empty-object-in-angular-2-template-using-ngif – Sudeep Sagar Nov 27 '19 at 06:39
0

You need to split the two-way-binding to one data and one event binding :-

[ngModel] = "orderLine?.price"
(ngModelChange) = "orderLine.price = $event"
Devanshi Mishra
  • 487
  • 5
  • 15
0

You cannot use ?. inside ngModel two-way binding, perhaps you can use ternary operator:

<input matInput placeholder = "Price" [(ngModel)]="orderLine? orderLine.price: null">
Mustahsan
  • 3,852
  • 1
  • 18
  • 34
0

we can not use ternary operator ? in two way binding

<input matInput placeholder = "Price" [(ngModel)]="orderLine?.price">

if your orderLine object something like below then you don't need to use this operator...

    orderLine= new OrderLine();

    class OrderLine {
         ...
         price: number;
         ...
    }
Ganesh
  • 5,808
  • 2
  • 21
  • 41
0

You need to split two-way binding.

[ngModel]="orderLine?.price" (ngModelChange)="orderLine.price = $event"
VSM
  • 1,765
  • 8
  • 18
Avtar
  • 11
  • 1
  • 5