奇怪的Angular2模型绑定问题

时间:2016-04-04 19:43:14

标签: angular angular2-forms

我遇到了Angular2上的模型绑定没有按照我的预期绑定的地方,而且我在确定出错的地方时遇到了问题。

我有一个对象数组如下:

commands = [
    {
        "id": 2,
        "command": "!first",
        "action": "This is the first command. You found it!",
        "reply": false
    },
    {
       "id": 5,
        "command": "!hi",
        "action": "Hello, how are you today?",
        "reply": true
    },
    ...
];

视图模板如下(为简洁起见,仅显示带有相关Angular2信息的标签):

<form #commandForm="ngForm">
    <tr *ngFor="#cmd of commands">
        <td *ngIf=" ! isEditingCommand(cmd)">{{ cmd.command }}</td>
        <td *ngIf="isEditingCommand(cmd)">
            <input type="text" class="form-control" placeholder="!command" required [(ngModel)]="cmd.command" (ngModelChange)="cmd.command=cleanCommand($event)" ngControl="cmd" #cmd="ngForm">
        </td>
        <td *ngIf=" ! isEditingCommand(cmd)">{{ cmd.action }}</td>
        <td *ngIf="isEditingCommand(cmd)">
            <textarea class="form-control" rows="1" placeholder="Text to display." required [(ngModel)]="cmd.action" ngControl="action" #action="ngForm"></textarea>
        </td>
    </tr>
</form>

isEditingCommand(cmd) === false时,行显示如下:

State when not editing the command

isEditingCommand(cmd) === true时,这就是我得到的:

State when editing the command

我已将cmdcmd.command更改为各种名称,如果command是Angular2的保留字,则无效。当我在视图中放置{{ cmd | json }}时,我收到此异常:

EXCEPTION: TypeError: Converting circular structure to JSON in [
                {{ cmd | json }}
             in CommandComponent@24:199]

遗憾的是,我无法确定这是如何形成圆形结构的。即使通过Chrome Inspector,我也找不到可能是圆形的地方。

locals from Chrome Inspector

为了提供帮助,以下是视图中定义的函数(TypeScript给我带来了问题;我稍后会重构它):

CommandComponent.prototype.cleanCommand = function (value) {
    value = value.replace(/[^a-z]+/gi, '');
    if (0 >= value.indexOf('!') && '!' !== value.substr(0, 1)) {
        value = '!' + value;
    }

    return value;
};
CommandComponent.prototype.isEditingCommand = function (command) {
    if (null === this.currentCommand) {
        return false;
    }

    return this.editFormActive && this.currentCommand.id === command.id;
};
// These are not used by the template shown, but they set values used in the functions.
CommandComponent.prototype.editCommand = function (command) {
    this.editFormActive = true;
    this.currentCommand = command;
};
CommandComponent.prototype.cancelEditCommand = function () {
    this.editFormActive = false;
    this.currentCommand = null;
};

环境:

  • Angular 2.0.0-beta.13
  • RxJS 5.0.0-beta.2
  • Zone.js 0.6.8

我做错了什么?如果需要更多信息,请告诉我,谢谢!

1 个答案:

答案 0 :(得分:2)

我不确定我是否理解你的问题。但是,我只看到一个可能导致一些约束问题的问题。

在这一行:

<input type="text" class="form-control" placeholder="!command" required [(ngModel)]="cmd.command" (ngModelChange)="cmd.command=cleanCommand($event)" ngControl="cmd" #cmd="ngForm">

您重新定义了本地变量cmd。第一个是*ngFor="#cmd of commands"。另一个#cmd="ngForm"。因此,与cmd.command的绑定将是cmd ngForm而不是#cmd of commands。换句话说,您已将新属性command添加到ngForm

这将解释循环引用问题,因为ngForm属于NgFormName,其_parent引用。