【发布时间】:2016-06-04 00:43:13
【问题描述】:
我创建了一个用作开关的组件。您可以像使用复选框一样使用它。这是一个精简版。
my-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);
}
}
我的计划是这样使用它:
父组件.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}}
我认为被迭代的项目是只读的。我知道我可以解决这个问题,但我想知道我正在尝试做的事情是否可行或不明智,以及为什么它不起作用。
【问题讨论】: