繁体   English   中英

* ngFor中的双向数据绑定

[英]Two-Way data binding in *ngFor

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

我-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);
    }
}

我的计划是这样使用它:

家长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)
    }   
}

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

{options: {option1: false}}

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

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

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

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

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

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

(valueChange)='logItem(item)'>

Plunker


我也建议

console.log(JSON.stringify(item))

在父子场景中,您可以利用xxxChange Output property的双向绑定,如下所示,
在父 - [(xxx)]="someValue"
在Child中 - @Input xxx: boolean;
@Output() xxxChange = new EventEmitter <boolean> ();

注意xxxChange属性。 在你的情况下缺少

现在, 在这里查看代码 - Plunker

<td> From Parent - {{item.options.option1}}   <--------------------value will keep changing
                     <my-switch 
                       [(value)]='item.options.option1'>  <---------two way binding
                     </my-switch>
 </td>

请注意, [()]表示双向绑定,因此在父级中您不需要使用(valueChange)="someValue=$event"来捕获更改。 [(value)]='item.options.option1'会自动将新的或更改的值绑定到item.options.option1


export class MySwitchComponent {

    @Input() value: boolean;
    @Output() valueChange = new EventEmitter <boolean> ();  <----xxxChange output property

...
...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM