为什么 Angular 2 绑定在这种情况下不起作用?(子组件输入字段)



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

现在我...

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

然后,我希望输入字段也重置为"开始",但它会继续显示步骤 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');
    }
}

是的,这是正确的行为。

由于在 Subcomp 中仅使用单向数据绑定,因此更改输入字段中的文本时,todo.title的值不会更改。

当调用update()时,会创建一个新的Todo对象,但todo.title的值是start的,因此当角度变化检测查看[ngModel]="subtodo.title"时,它看不到任何变化 - subtodo.title的旧值start当前值也是如此。 角度变化检测按值比较基元类型(数字、字符串、布尔值)。

为了证明这一点,请尝试以下操作:

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

或者试试这个:

<input type="text" [(ngModel)]="subtodo.title">

最新更新