代码之家  ›  专栏  ›  技术社区  ›  CHARAFI Saad

角度5:投射任意到对象

  •  1
  • CHARAFI Saad  · 技术社区  · 6 年前

    我使用角度5,我想为任意到对象类型的对象投射。

    <select #selectedSupplier (change)="onSelectSupplier(selectedSupplier.value)">
        <option *ngFor="let supplier of suppliers" [value]="supplier">                                                                                                                                                
            {{ supplier.name }}
        </option>
    </select>
    

    当我试图用这个函数在控制台上显示结果时

    // Result is [object Object]
    onSelectSupplier(supplier){
        console.log(supplier);
    }
    
    // Result is undefined
    onSelectSupplier(supplier){
        console.log(supplier.name);
    }
    

    所以我想投供应商:任何到我下面的对象

    export class Supplier{
        name: string;
    
        constructor(name: string){
            this.name=name;
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   user184994    6 年前

    类型只存在于运行时,所以这不能解决问题。

    实际上,问题是 [value] ,因为这只处理字符串。这就是它被转换成[对象对象对象](实际上是一个字符串)的原因。你应该用 ngValue 对于对象。我也建议你用 ngModel ,就像这样:

    <select #selectedSupplier [(ngModel)]="selected" (change)="onSelectSupplier(selected)">
        <option *ngFor="let supplier of suppliers" [ngValue]="supplier">                                                                                                                                                
            {{ supplier.name }}
        </option>
    </select>
    

    Here is a Stackblitz demo