在角度 7 中设置可能为空的输入字段的值



我正在使用以下内容在输入字段中放置值。 使用 Angular 6 设置输入字段的值

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

但是,有时该值可能为空。放置问号时?下面,我们收到以下错误,有人如何在输入中放置可能的空白 null 值,或者不可能?

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

"?."运算符不能在 [[orderLine?] 中的赋值列中使用。产品名称=$event]

请将其分成两部分,因为这两个部分是 ngModel

: 的一部分:
[ngModel]="orderLine?.price" (ngModelChange)="orderLine.price = $event"

你不能在 ngModel 双向绑定中使用?.,也许你可以使用三元运算符:

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

我们不能在双向绑定中使用三元运算符?

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

如果你的orderLine对象如下,那么你不需要使用这个运算符......

orderLine= new OrderLine();
class OrderLine {
...
price: number;
...
}

您需要将双向绑定拆分为一个数据和一个事件绑定:-

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

您需要拆分双向绑定。

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