簡體   English   中英

在 Angular 7 中設置可能為空的輸入字段的值

[英]Setting values of Input fields with possible null in Angular 7

我正在使用以下內容在輸入字段中放置值。 使用 Angular 6 設置輸入字段的值

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

但是,有時該值可能為空。 什么時候打問號? 下面,我們收到以下錯誤,有人如何在輸入中放置可能的空白空值,或者不可能?

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

這 '?。' 運算符不能在 [[orderLine?.productname=$event] 中的列賦值中使用

請把它分成兩部分,因為這兩部分是 ngModel 的一部分:

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

您需要將雙向綁定拆分為一個數據和一個事件綁定:-

[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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM