2015-11-18 60 views
1

我试图根据我得到的数据从服务器获取响应后创建元素。是否有可能创建将在获取新数据后更新DOM的组件?即加载后的角度2 DOM操作

<table> 
    <thead> 
    <tr> 
     <th>First name</th> 
     <th>Last name</th> 
    </tr> 
    </thead> 
    <tbody> 
    ... 
    </tbody> 
</table> 

我想在加载页面后用angular2组件构建这样的表。我试图用对组件

@Component({ 
    selector: 'thead', 
    template: ` 
    <tr> 
     <th *ng-for="#th of tableHeaders">{{ th.name }}</th> 
    </tr> 
    ` 
}) 
export class TableHeader { 
    tableHeaders: Array<any>; 

    constructor() { 
    this.tableHeaders = []; 
    } 

    addHeader(header) { 
    this.tableHeaders.push(header) 
    } 
} 

和其他地方

... 
this.http.get('/some/url') 
    .map(res: Response => res.json()) 
    .subscribe(
     (data: any) => { 
      for (var i = 0; i < data.tableColumns.length; i += 1) { 
      TableHeader.addHeader(data.tableColumns[i]) 
      } 
     } 
    ) 
... 

我在正确的方向白衣的是要做到这一点?

回答

0

没有一个plnkr,我不知道你遇到了什么。但也许你可以通过使用NgZone来解决这个问题。用法如下。

import {NgZone} from 'angular2/angular2' 

constructor(private ngZone:NgZone) 
{ 
    this.ngZone.run(
    () => { 
     //code to update view like add a item to array. 
    } 
) 
} 
0

我用简单的类属性解决了这个问题。我只需要在我的父组件上使用@ViewChild。感谢帮助。

0

我更喜欢使用服务,因此它可以作为数据提供者。

可以在此处找到示例,单击添加按钮将获得http.get中的人员列表,并将结果追加到现有人员数组中。

http://plnkr.co/edit/NCxUCAPTqZUc0Gbpey6v?p=preview

//a simple service 
import {Injectable} from 'angular2/angular2'; 
import {Http} from 'angular2/http'; 

@Injectable() 
export class PeopleService { 
    constructor(http:Http) { 
    this.people = http.get('api/people.json').map(res => res.json()); 
    } 
} 

然后调用订阅获得您的组件人民阵列。

//our root app component 
import {Component, View, CORE_DIRECTIVES} from 'angular2/angular2' 
import {PeopleService} from './peopleService' 
import {Person} from './person' 

@Component({ 
    selector: 'my-app', 
    providers: [PeopleService] 
}) 
@View({ 
    template: ` 
    <div> 
     <my-person *ng-for="#person of people" [name]="person.name"></my-person> 
    </div> 
    <button (click)="addName()">Add name</button> 
    `, 
    directives: [CORE_DIRECTIVES, Person] 
}) 
export class App { 
    people: Array<string>; 
    constructor(public peopleService:PeopleService) { 
    this.people = [ {"id": 0, "name": "Plunker"}]; 
    } 

    addName() { 
    var app = this; 
    this.peopleService.people.subscribe(data => Array.prototype.push.apply(app.people, data)); 
    } 
}