2

我有一个名为 AppComponent 的(Angular 2)根组件,它使用另一个名为 Subcomp 的组件。App 将@Input()参数传递给 Sub。Sub 使用此变量在输入字段中进行单向绑定。

现在我...

  1. 将参数的值设置为某个初始值(“start”);这按预期显示在输入字段中。
  2. 将输入字段中的文本更改为其他内容。
  3. 单击按钮以编程方式将 AppComponent 中的值重置为“开始”。

然后我希望输入字段也重置为“开始”,但它会继续显示步骤 2 中更改的文本。这是正确的行为吗?

编码:

class Todo {
    constructor(public title: string) {}
}

@Component({
    selector: 'subcomp',
    directives: [FORM_DIRECTIVES],
    template: `New Title: <input type="text" [ngModel]="subtodo.title">`
})
export class Subcomp {
    @Input() subtodo: Todo;
}

@Component({
    selector: 'my-app',
    directives: [Subcomp],
    template: `To do: {{todo.title}}<br/>
               <subcomp [subtodo]="todo"></subcomp><br/>
               <button (click)="update()">Update</button>`
})
export class AppComponent {

    todo: Todo = new Todo('start');

    update() {
        this.todo = new Todo('start');
    }

}
4

1 回答 1

1

是的,这是正确的行为。

因为您只在 中使用单向数据绑定,所以当您更改输入字段中的文本时Subcomp, 的值todo.title不会改变。

update()被调用时,会创建一个新Todo对象,但是 的值todo.titlestart,所以当 Angular 变化检测查看 时[ngModel]="subtodo.title",它看不到任何变化 - 的旧值和当前值一样subtodo.titlestart角度变化检测按值比较原始类型(数字、字符串、布尔值)。

为了证明这一点,试试这个:

update() {
    this.todo = new Todo('start' + new Date());
}

或试试这个:

<input type="text" [(ngModel)]="subtodo.title">
于 2016-02-12T19:07:49.920 回答