繁体   English   中英

如何在Angular中更改模型后更新视图?

[英]How to update the view after changing the model in Angular?

如何让Angular将我所做的更改传播到模型中。 在AngularJS中,这将非常简单,但我似乎无法让它在Angular中运行。 我知道整个变化检测系统和视图传播完全改变了。 不知何故,我需要通知角度变化。 但是我怎么能在实践中做到这一点。

看到这段打字稿代码:

import {Component, View, bootstrap, For} from 'angular2/angular2';

// Annotation section
@Component({
    selector: 'app'
})
@View({
    template: `
    <div *for="#user of users">
        {{user}}
    </div>
    `,
    directives: [For]
})
class App {
    users:Array<String>;

    constructor() {
        this.users = [];
        this.fillUsersAsync();
    }

    fillUsersAsync(){
        window['fetch']('http://jsonplaceholder.typicode.com/users')
            .then( resp => resp.json())
            .then( users => users.forEach(user => this.users.push(user.name)))
            .then( () => console.log('Retrieved users and put on the model: ', this.users));
    }
}

bootstrap(App);

您将看到,在用户加载到模型后,视图不会更新。

我正在使用systemjs 0.16,角度2.0.0-alpha.23。

请参阅此plnkr示例 (目前仅适用于chrome,因为使用了新的' fetch'api

我发现了这个问题。 显然,它是一个在alpha 27中修复的错误。请参阅此错误报告: https//github.com/angular/angular/issues/1913

Angular2使用zonejs知道何时开始摘要循环(脏检查和更新视图)。 截至目前,在使用新的window.fetch()获取数据后,不会触发zonejs。

将窗口['fetch']行替换为this修复了我的问题: Zone.bindPromiseFn(window['fetch'])('http://jsonplaceholder.typicode.com/users')

要在AngularJS2中更新视图中的数据,您应该使用Forms 您可以在此页面阅读此内容或在此处查看更多详细信息。 如果我正确理解了表单,你应该修改你的@View部分,如下所示:

@View({
    template: `
    <div *for="#user of users" control="users">
        {{user}}
    </div>
    `,
    directives: [For]
})

--edited

试试这个:

import {Component, View, bootstrap, For} from 'angular2/angular2';

// Annotation section
@Component({
    selector: 'app'
})
@View({
    template: `
    <div [control]="users" *for="#user of users">
        {{user.value}}
    </div>
    `,
    directives: [For, forms]
})
class App {
    users:Array<String>;

    constructor() {
        this.users = new Control([]);
        this.fillUsersAsync();
    }

    fillUsersAsync(){
        window['fetch']('http://jsonplaceholder.typicode.com/users')
            .then( resp => resp.json())
            .then( users => 
                var usersArr = []
                users.forEach(user => 
                      usersArr.push(user.name))
                this.users = new Control(usersArr));
        }
 }

 bootstrap(App);

我不确定我的答案是否完全正确,但我找不到更多信息。 尝试使用此代码,力量可能与您同在! :)

我也找到了这个链接非常有用。

据我所知,在构造函数中,您应该通过new Control(some data)初始化您的users变量,然后在视图模板中,您可以像这样访问这些数据 - {{users.value}}

如果它不起作用:尝试相同但使用非常简单的数据,例如使用字符串而不是数组。

此视频将有助于在ng2中展示表单。

刚刚在这里回答了Angular2视图在更新数据后没有更改

基本上,Beta 2.0.0-beta.1中存在一个错误。

希望能帮助到你!

Ng前缀又回来了。 For现在已成为ngFor版本alpha-24 +的ngFor。

import {NgFor} from 'angular2/directives';
@View({
  directives: [ngFor]
})

然后在模板中使用*ng-for=#user of users"

查看ngFor文档工作示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM