angularjs - 绑定(bind)到对象的属性在 Angular 2 中不起作用

标签 angularjs angular property-binding

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

首先,这是一个 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>

这里是绑定(bind) [value]="s"option<select>标签只是不起作用!它设置 selectedStore对于一些空对象(?),它显示空 Address:文本在 <small>标签,它会记录: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>

现在绑定(bind)工作了,地址被记录在控制台中,也显示在 <small> 中。正确标记。所以绑定(bind) [value]="s"不起作用(实际上给出了一些奇怪的“对象”值),但绑定(bind) [value]="s.address"按预期工作。我已经按照文档进行操作,但没有提及此类限制。这是一个错误吗?还是我遗漏了什么?

最佳答案

[value] 仅支持字符串值作为绑定(bind)值。使用 [ngValue] 代替,它可以绑定(bind)对象。

关于angularjs - 绑定(bind)到对象的属性在 Angular 2 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40578305/

相关文章:

javascript - 无法使用 ng-repeat 打印对象的值

javascript - 使用 Protractor 或 JavaScript 的浏览器后退按钮

angular - 反向映射字符串枚举 Angular 4

angular - 从单个文档 Angular 和 Firestore 检索值

ios - SwiftUI 显示基于计算属性的警报

wpf - Xamarin.Forms BindableProperty 和 WPF DependencyProperty 之间的区别

angularjs - Angular : ng-show and functions

javascript - AngularJS $window.confirm 在 Chrome 中不工作

angular - 如何获取 Angular 2 应用程序的根 viewContainerRef