*ngFor中的双向数据绑定

thr*_*eve 4 angular2-template angular

我创建了一个组件,意在成为一个开关.您可以像使用复选框一样使用它.这是一个精简版.

我-switch.component.ts:

import {Component, Input, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'my-switch',
    template:    `<a (click)='toggle()'>
                    <span *ngIf='value'>{{onText}}</span>
                    <span *ngIf='!value'>{{offText}}</span>
                  </a>`
})
export class MySwitchComponent {
    @Input() onText: string = 'On';
    @Input() offText: string = 'Off';
    @Input() value: boolean;

    @Output() change = new EventEmitter <boolean> ();

    position: string;

    toggle() {
        this.value = !this.value;
        this.change.emit(this.value);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的计划是这样使用它:

家长component.ts

import {Component} from '@angular/core';
import {MySwitchComponent} from 'my-switch.component';

@Component({
    selector: 'my-sites',
    directives: [MySwitchComponent]
    template: `<table>
                 <tr *ngFor='let item of items'>
                   <td>
                     <my-switch 
                       [(value)]='item.options.option1'
                       (change)='logItem(item)'>
                     </my-switch>
                   </td>
                 </tr>
               </table>`
})
export class MySitesComponent {
    items: Object[] = [
        {options: { option1: false }}
    ];

    logItem(item) {
        console.log(item)
    }   
}
Run Code Online (Sandbox Code Playgroud)

同样,这是简化的,但我认为说明了我的期望.我的期望是,当单击开关时,视图会从"关闭"更新为"开",并且会记录该选项的值.问题是记录的值如下所示:

{options: {option1: false}}
Run Code Online (Sandbox Code Playgroud)

我的信念是迭代的项目是只读的.我知道我可以解决这个问题,但我想知道我想做的事情是可能的,还是不明智的,以及为什么它不起作用.

Mar*_*cok 6

Angular将[(x)]语法"解糖" x为属性绑定的输入属性和xChange事件绑定的输出属性.- 参考

因此,如果为输入属性命名,则value必须为输出属性命名valueChange:

@Output() valueChange = new EventEmitter <boolean> ();
Run Code Online (Sandbox Code Playgroud)

这是你想念的唯一一块拼图.您现在在父组件和子组件之间具有双向数据绑定.

如果要在子项更改emit()值时执行某些逻辑,请捕获(valueChange)父组件中的事件:

(valueChange)='logItem(item)'>
Run Code Online (Sandbox Code Playgroud)

Plunker


我也建议

console.log(JSON.stringify(item))
Run Code Online (Sandbox Code Playgroud)