Angular2:Map对象的双向绑定

ark*_*mvm 9 angular

我如何在Map对象上使用双向绑定?

以下代码无法按预期工作:

零件:

@Component({
    moduleId:    module.id,
    selector:    "my-component",
    templateUrl: "my-component.html",
    styleUrls:   ["my-component.scss"],
})
export class MyComponent {
    myMap: Map<string, Object> = Map<string, Object>()
        .set('first', {text: 'abc'})
        .set('second', {text: 'foo'})
    ;
}
Run Code Online (Sandbox Code Playgroud)

模板:

<div class="items" *ngFor="let item of myMap.values()">
    <input type="text" [(ngModel)]="item.text" />
</div>
Run Code Online (Sandbox Code Playgroud)

sho*_*ukh 3

实际上,在此示例中,双向数据绑定按预期工作。您的错误可能是创建 Map 对象:

myMap: Map<string, Object> = Map<string, Object>()
Run Code Online (Sandbox Code Playgroud)

您必须new在之前包含关键字Map(因为映射构造函数不可调用):

myMap: Map<string, Object> = new Map<string, Object>()
        .set('first', {text: 'abc'})
        .set('second', {text: 'foo'})
Run Code Online (Sandbox Code Playgroud)

现在一切都按预期进行。您也可以查看这个stackblitz 演示。

注意:根据GitHub 上的这个 Angular 问题:映射在键中没有顺序,因此它们的迭代是不可预测的。这在 ng1 中得到了支持,但我们认为这是一个错误,并且在 NG2 中不会得到支持。

最简单的解决方案之一是使用Array.from()方法 on myMap.entries()

getEntities() {
  // this will return [['first', { text: 'abc' }], ... ]
  // and after mapping we get [{ text: 'abc' }, ...]
  return Array.from(this.myMap.entries()).map(item => item[1]);
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以在模板中使用它:

<div class="items" *ngFor="let item of getEntities()">
  <input type="text" [(ngModel)]="item.text" />
</div>
Run Code Online (Sandbox Code Playgroud)

在此示例中,双向数据绑定也有效。