【问题标题】:Property binding to the object does not work in Angular 2与对象的属性绑定在 Angular 2 中不起作用
【发布时间】:2017-03-27 11:22:43
【问题描述】:

我在使用 Angular 2 属性绑定时遇到了非常奇怪的行为。

首先,这是一个 Store 类:

export class Store {
    id: number;
    name: string;
    address: string;
}

这是组件代码:

export class MyBuggyComponent implements OnInit {

  stores: Store[];
  selectedStore: any;
  error: any;

  constructor(private myDataService: MyDataService) { }

  ngOnInit() {
    this.myDataService.getStores().subscribe(
      stores => this.stores = stores,
      error => { this.error = error; console.log(this.error); });
  }

  selectionChanged(value: any){
    console.log("DEBUG: " + value);
  }
}

这是让我抓狂的模板!

<form>
  <div class="form-group">
    <label for="store">Select store:</label>
    <select class="form-control custom-select" id="store" name="store" required 
      [(ngModel)]="selectedStore" (change)="selectionChanged($event.target.value)">
      <option *ngFor="let s of stores" [value]="s">{{s.name}}</option>
    </select>
    <small class="form-text text-muted" *ngIf="selectedStore">Address: {{selectedStore.address}}</small>
  </div>
</form>

在这里绑定[value]="s"option&lt;select&gt; 标记不起作用!它将selectedStore 设置为某个空对象(?),它在&lt;small&gt; 标签中显示空Address: 文本,并在控制台中记录:DEBUG: [object Object](在selectionChanged() 中)。但{{s.name}} 插值按预期工作(在选择框中显示名称)。

现在看这个:如果我对模板进行以下修改,它就会按预期工作:

  <option *ngFor="let s of stores" [value]="s.address">{{s.name}}</option>
</select>
<small class="form-text text-muted" *ngIf="selectedStore">Address: {{selectedStore}}</small>

现在绑定工作了,地址已登录到控制台并正确显示在&lt;small&gt;标签中。所以绑定[value]="s" 不起作用(实际上给出了一些奇怪的“对象”值),但绑定[value]="s.address" 按预期工作。我已经关注了文档,没有提到这种限制。这是一个错误吗?还是我错过了什么?

【问题讨论】:

    标签: angularjs angular property-binding


    【解决方案1】:

    [value] 仅支持字符串值作为绑定值。改用[ngValue],可以绑定对象。

    【讨论】:

    • 我认为这应该清楚地记录在官方文档中,而不是在这篇文章中。
    【解决方案2】:

    我有同样的问题,你可以试试我的解决方案:

    <select class="form-control custom-select" id="store" name="store" required 
      [(ngModel)]="selectedStore" (change)="selectionChanged($event.target.value)">
      <option *ngFor="let s of stores; let i = index" value="{{i}}">{{s.name}}</option>
    </select>
    
    // .ts
    selectionChanged(value: any){
       // this.selectedStore = position in stores
       console.log(this.stores[this.selectedStore]);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-26
      • 1970-01-01
      • 2015-10-08
      • 2017-06-16
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      相关资源
      最近更新 更多