user12425844
user12425844

Reputation:

Setting values of Input fields with possible null in Angular 7

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]

Upvotes: 1

Views: 3342

Answers (5)

Avtar
Avtar

Reputation: 11

You need to split two-way binding.

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

Upvotes: 0

Dv6
Dv6

Reputation: 489

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

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

Upvotes: 0

Sudeep Sagar
Sudeep Sagar

Reputation: 253

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

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

Upvotes: 2

Ganesh
Ganesh

Reputation: 6016

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

Upvotes: 0

Mustahsan
Mustahsan

Reputation: 3862

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

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

Upvotes: 0

Related Questions