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]

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

5 Answers 5

2

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

[ngModel]="orderLine?.price" (ngModelChange)="orderLine.price = $event"
Sign up to request clarification or add additional context in comments.

3 Comments

what if there is no field (price) is presented in the orderLine object..?
whats the difference between Mutsahen answer and yours? both seem good by the way, maybe just different flavors of doing things,
@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:: stackoverflow.com/questions/37111005/…
0

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

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

Comments

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;
         ...
    }

Comments

0

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

[ngModel] = "orderLine?.price"
(ngModelChange) = "orderLine.price = $event"

1 Comment

what if there is no field (price) is presented in the orderLine object..?
0

You need to split two-way binding.

[ngModel]="orderLine?.price" (ngModelChange)="orderLine.price = $event"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.