【问题标题】:Angular 5 Material Update mat-select when List of mat-options Change当垫子选项列表更改时,Angular 5 Material Update mat-select
【发布时间】:2018-05-17 21:12:23
【问题描述】:

在我的 Angular 5 应用程序中,我有一个输入框,当按下回车键时,它会调用一个返回数组的 API。然后在 mat-select 中使用该数组来填充 mat-options。第一项被自动选中,但显示值永远不会更新。

换句话说,当 mat-select 填充动态数据时,对其 ngModel 的赋值不会反映在其显示值中。

component.html:

<mat-form-field>
    <input matInput placeholder="Order ID" [(ngModel)]="orderID (keydown)="handleKeyDown($event)">
</mat-form-field>

<mat-form-field>
    <mat-select placeholder="Product ID"  (change)="showProductDetails(productID)" [(ngModel)]="productID" >
        <mat-option *ngFor="let product of products" [value]="product.id"> {{ product.name }} </mat-option>
    </mat-select>
</mat-form-field>

component.ts:

orderID = '';
products = [];

handleKeyDown(event: any) {
  if (event.keyCode === 13) { this.getProductIDs(); }
}

getProductIDs(){

    ... /~ Call API and populate "products"  ~~/

    // Update the mat-select's ngModel - value is updated but display is not
    productID = products[0].id;
}

showProductDetails(productID){ /~~ Do some stuff }

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    Angular Material 文档中的一个示例:

    所以你应该使用[(value)] 而不是普通的[(ngModel)],像这样:

    <mat-form-field>
        <mat-select placeholder="Product ID"  (change)="showProductDetails(productID)" [(value)]="productID" >
            <mat-option *ngFor="let product of products" [value]="product.id"> {{ product.name }} </mat-option>
        </mat-select>
    </mat-form-field>
    

    【讨论】:

    • 感谢您的帮助。在这种情况下, value 和 ngModel 的执行方式相同。这个问题实际上与一个浏览器扩展程序有关,因为它认为它是一个电话号码,所以它剥离了 ID。不管怎样,都解决了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2018-10-17
    • 2018-08-17
    • 2018-05-17
    相关资源
    最近更新 更多