【问题标题】:Why does Angular 2 binding not work in this case? (sub component input field)为什么 Angular 2 绑定在这种情况下不起作用? (子组件输入字段)
【发布时间】:2016-05-23 19:28:01
【问题描述】:

我有一个名为 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');
    }

}

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    是的,这是正确的行为。

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

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

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

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

    或者试试这个:

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

    【讨论】:

    • 好的,这很有意义,即使它在使用时看起来违反直觉。谢谢!
    • update() 创建的new Todo('xxx') 具有不同的值时,它仍然不会更新输入。也不是 Todo ngModel 绑定到一个简单的字符串字段。对我来说,它仍然看起来像一个错误。
    • @GünterZöchbauer,这个plunker 表明new Todo('start' + new Date()) 确实更新了输入。 (使用 Beta.0,如果这很重要。我还没有放弃它,因为它似乎有更少的错误。)
    • 对,您已经在回答中提到了它。感谢Plunker。看来我尝试时犯了一个错误。现在它也可以在 Dart 中以这种方式工作。
    猜你喜欢
    • 2017-11-26
    • 2010-12-29
    • 1970-01-01
    • 2021-08-05
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多