【问题标题】:binding datatable dynamically in angular2 not working在angular2中动态绑定数据表不起作用
【发布时间】:2017-03-18 04:04:00
【问题描述】:

我正在使用 Smart Admin Template 以表格格式显示数据。

我尝试将数据与硬编码数据绑定,但当我从 ngOnInit 上的 component.ts 中点击 service.ts 并设置为 this.data 时。虽然设置但不显示到ui/component.html。

请看下面的代码。如果需要更多帮助,请告诉我。

1.在我写的component.html里面:-

    <sa-datatable ng-data="data" [options]="{
                colReorder: true,
                data: data,
                columns: [ {data: 'apiKey'}, {data: 'name'}]}"
                paginationLength="true" tableClass="table table-striped table-bordered table-hover" width="100%">
                                <thead>
                                    <tr>
                                        <th data-hide="phone">APIKey</th>
                                        <th data-class="expand">
                                            <i class="fa fa-fw fa-user text-muted hidden-md hidden-sm hidden-xs"></i>
                                            Name
                                        </th>
                                    </tr>
                                </thead>
</sa-datatable>

2。内部组件.ts

import { Component, OnInit } from '@angular/core';
import {JsonApiService} from "../shared/api/json-api.service";
import {Observable} from 'rxjs/Rx';
import {Router, CanActivate }    from '@angular/router';

@Component({
    selector: 'administration-apps',
    templateUrl: './administration.apps.component.html',
    styleUrls: ['./administration.component.css'],
    providers: [JsonApiService]
})

export class AdministrationAppsComponent implements OnInit {
    //data = [{ "_id": "5807f24c762c48a0b548318f", "accountID": "580170af762c48a0b548318e", "name": "EZ FORMSTest 4", "active": true, "apiKey": "b2878c30-bea0-11e4-983f-d9ec76fdf276" }, { "_id": "580170af762c48a0b008318e", "accountID": "580170af762c48a0b54831ff", "name": "EZ FORMSTest 5", "__v": 0, "active": true, "apiKey": "b2878c30-bea0-11e4-983f-d9ec76fdf276" }];

    private data: any;
    private errorMessage: string;
    constructor(private jsonApiService: JsonApiService, private router: Router) {
    }
    createNewApp() {
        this.router.navigate(['/administration/apps/new'])
    }
  ngOnInit() {
      this.data = this.jsonApiService.getApps()
          .subscribe((apps: any) => { this.data = apps; console.log('looking for data now'); console.log(this.data);},
              error => this.errorMessage = error);
  }

}

3. json-api.service.ts内部

getApps(): any {
  return this.httpGet('/app');
}
  httpGet(path) {
  let headers = new Headers({ 'X-TOKEN': '2f348e80-a26c-11e6-aea2-     b1b9938df75f' });
  let options = new RequestOptions({ headers: headers });
  return this.http.get(this.baseURL + path, options)
      .map((res: Response) => res.json())
      .map(forms => {
          return forms;
      })
      .catch(this.handleError);
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    我试图通过从 API 获取响应来绑定数据表。

    组件在获取 api 响应数据之前加载。

    为此,我在运行时加载了组件。

    动态加载组件有几个步骤:-

    1.创建动态组件dynamic.component.ts

       import {Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector,           
       ComponentFactoryResolver} from '@angular/core';
       import {AdministrationAppsDatatableComponent} from         
      './administration.apps.datatable.component';
    
      @Component({
     selector: 'dynamic-component',
     entryComponents: [AdministrationAppsDatatableComponent], // Reference to the     
     components must be here in order to dynamically create them
     template: `<div #dynamicComponentContainer></div>`,
     })
     export class DynamicComponent {
     currentComponent = null;
    
     @ViewChild('dynamicComponentContainer', { read: ViewContainerRef })     
     dynamicComponentContainer: ViewContainerRef;
    
    // component: Class for the component you want to create
    // inputs: An object with key/value pairs mapped to input name/input value
    @Input() set componentData(data: { component: any, inputs: any }) {
        if (!data) {
            return;
        }
    
         // Inputs need to be in the following format to be resolved properly
        let inputProviders = Object.keys(data.inputs).map((inputName) => { return { provide: inputName, useValue: data.inputs[inputName] }; });
        let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
    
        // We create an injector out of the data we want to pass down and this components injector
        let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicComponentContainer.parentInjector);
    
        // We create a factory out of the component we want to create
        let factory = this.resolver.resolveComponentFactory(data.component);
    
        // We create the component using the factory and the injector
        let component = factory.create(injector);
    
        // We insert the component into the dom container
        this.dynamicComponentContainer.insert(component.hostView);
    
        // We can destroy the old component is we like by calling destroy
        if (this.currentComponent) {
            this.currentComponent.destroy();
        }
    
        this.currentComponent = component;
    }
    
    constructor(private resolver: ComponentFactoryResolver) {
    
    }
    }
    

    2。创建了 Administration.apps.datatable.component.ts

    import {Component, Injector} from '@angular/core';
    
    @Component({
    selector: "adminAppsHtml",
    template: `<sa-datatable [options]="tblOptions"
                                          paginationLength="true"  
    tableClass="table table-striped table-bordered table-hover"
                                          width="100%">
                <thead>
                    <tr>
                        <th>APIKey</th>
                        <th>Name</th>
                    </tr>
                </thead>
            </sa-datatable>
    
      `
      })
    
      export class AdministrationAppsDatatableComponent {
     tblOptions = {};
     constructor(private injector: Injector) {
        this.tblOptions = this.injector.get('options');
        console.log('looking for options in admin apps')
        console.log(this.tblOptions);
      }
    } 
    

    3.在 component.html 中这样写:- 你想在哪里显示你的数据表记录。

    <dynamic-component [componentData]="componentData"></dynamic-component>
    

    3 在调用 API 的组件中包含 Administration.apps.datatable.component,例如在 ngOnInit() 方法和模块中。

    import {AdministrationAppsDatatableComponent} from  
    "./administration.apps.datatable.component";
    ngOnInit() {
        this.jsonApiService.getApps()
          .subscribe((apps) => {          
          this.componentData = {
              component: AdministrationAppsDatatableComponent,
              inputs: {
                  options: {
                      colReorder: false,
                      data: apps,
                      columns: [{ data: 'apiKey' }, { data: 'name' }]
                  }
              }
          };
          },
          error => this.errorMessage = error);
    

    }

    要运行示例,请点击我关注的链接

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

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 2016-08-20
      • 2016-10-02
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      相关资源
      最近更新 更多