将数据传输到另一个组件的角网格网格

问题描述 投票:0回答:1

找到了解决方案。实际上,一个好朋友帮助了我。稍后再发布。

我被卡住了!我似乎无法将数据传递给(大)子组件。我可以在路由中传递ID,并且ID会显示在URL中,但是我似乎无法访问任何数据。我在下面添加代码。我已经尝试了一切!是因为数据是从ag-grid模型传递的,所以无法传递给孙子孙?如何将数据传递到列表组件?我将添加其余代码以显示我尝试过的内容。

原始消息:我有一个ag-grid,其中一个字段是CellRenderer,它创建一个按钮。我试图将数据传递到cellRenderer中,所以当用户单击按钮时,数据将传输到该组件,然后将其显示为列表或模式。

我的带有网格ts文件的组件:


import { Component, OnInit } from '@angular/core';
import { ReportService } from 'src/app/services/report.service';
import { Report } from 'src/app/models/report';
import { agThemeSgBootstrap } from "@sg-bootstrap/ag-grid";
import { GridOptions } from 'ag-grid-community';
import { DatePipe } from '@angular/common';
import {ViewMoreButtonComponent} from "./view-more-button/view-more-button.component";


@Component({
  selector: 'app-report',
  templateUrl: './report.component.html',
  styleUrls: ['./report.component.scss']
})
export class ReportComponent implements OnInit {

  apiUrl: any;
  reports : Report[];
  gridOptions: GridOptions;
  dateValue = new Date();
  maxDate = new Date();
  private frameworkComponent;

  columnDefs = [
    {headerName: 'Report Name', field: 'reportName', resizable: true,
      valueGetter: params => { return `${params.data.reportName}.dat` }},
    {headerName: 'Sent to FIS', field: 'sentToFis',resizable: false,
      valueGetter: params => { return params.data.sentToFis === true ? "Yes" : "No"  } },
    {headerName: 'File Size', field: 'contentLength', resizable: true,
      valueGetter: params => { return `${this.formatBytes(params.data.contentLength)}` }},
    {headerName: 'Last Modified', field: 'lastModified', resizable: true,
      valueGetter: params => { return this.datePipe.transform(params.data.lastModified, "yyyy-MM-dd HH:mm:ss") }},
    {headerName: '', field: 'value', resizable: false,
      cellRendererFramework: ViewMoreButtonComponent, width: 180, colId: 'params',
      valueGetter: params => {return `${params.data.id}`}}

  ];

  constructor(private reportService : ReportService, private datePipe: DatePipe) {
    this.frameworkComponent = {
      viewMoreButtonComponent: ViewMoreButtonComponent
    };
  }

  ngOnInit() {
    this.callReportService(new Date())

  }

  reportDateChange(value: Date) {

    let currentValue = this.datePipe.transform(this.dateValue, "yyyyMMdd")
    let newSelectedValue = this.datePipe.transform(value, "yyyyMMdd")
    if (currentValue != newSelectedValue) {
      if (this.gridOptions.api) {
        this.gridOptions.api.showLoadingOverlay();
      }
      this.callReportService(value)
      this.dateValue = value;
    }
  }

  callReportService(value: Date) {
    this.reportService.getReportsForDate(value).subscribe(x=> {
      this.reports = x;
      this.gridOptions.api.sizeColumnsToFit();

    })
  }

  ngAfterContentInit() {
    let agOpt = { ...{
      animateRows: true,
        enableRangeSelection: true,
        defaultColDef: {
          editable: false,
          enableValue: false,
          enableRowGroup: false,
          enablePivot: true,
          filter: true,
          sortable: true
        },
      statusBar: {
        statusPanels: [{
            statusPanel: 'agTotalRowCountComponent',
            align: 'left'
          },
          {
            statusPanel: 'agFilteredRowCountComponent'
          },
          {
            statusPanel: 'agSelectedRowCountComponent'
          },
          {
            statusPanel: 'agAggregationComponent'
          },
        ],
      }
     }, ...agThemeSgBootstrap }
    this.gridOptions  = { ...this.gridOptions, ...agOpt }
  }

  onGridReady(params) {
    params.api.setDomLayout("autoHeight");
    params.api.sizeColumnsToFit();
  }

  onGridSizeChanged(params) {
    params.api.sizeColumnsToFit();
  }

  ngAfterViewInit() {

    this.dateValue = new Date()


  }

  formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}


}

我的按钮组件

import {ICellRendererAngularComp} from "@ag-grid-community/angular";
import {Report} from "../../../../models/report";
import {ReportService} from "../../../../services/report.service";

@Component({
  selector: 'app-view-more-button',
  templateUrl: './view-more-button.component.html',
  styleUrls: ['./view-more-button.component.scss']
})
export class ViewMoreButtonComponent implements ICellRendererAngularComp {
  // @Input() id: Report;
  public params: any;
  reports: Report[];


  agInit(params: any) {
    this.params = params;
    console.log(this.data.params.id);

  }

  constructor(reportService: ReportService) { }


  ngOnInit() {

  }

public ViewMore() {
    // this.reportService.
    // this.params.context.componentParent.methodFromParent(`Row:
    // ${this.params.node.rowIndex}, Col: ${this.params.colDef.headerName}`)
  }

  refresh(): boolean {
    return false;
  }

}


我查看更多按钮组件html文件

<app-view-more [params]="params.data" > ></app-view-more>>

<button class="viewMoreButton" mat-stroked-button routerLink="/viewmore/{{params.data.id}}">View More</button>

我的孙子组件

import {Component, Input, OnInit} from '@angular/core';
import {Report} from "../../../../../models/report";
import {ReportService} from "../../../../../services/report.service";
import {ViewMoreButtonComponent} from "../view-more-button.component";

@Component({
  selector: 'app-view-more',
  templateUrl: './view-more.component.html',
  styleUrls: ['./view-more.component.scss']
})
export class ViewMoreComponent implements OnInit{
  @Input() params: any[] ;
constructor()   { }

    // getReportDetails() {
    // this.reportService.getParams().subscribe(data => {
    //   this.reportDetail = data;
    // })
    // }
  ngOnInit(): void {
    console.log(this.params[0]);
    // console.log(this.params.reportName);
   }

  }
my parent component

import { Component, OnInit } from '@angular/core';
import { ReportService } from 'src/app/services/report.service';
import { Report } from 'src/app/models/report';
import { agThemeSgBootstrap } from "@sg-bootstrap/ag-grid";
import { GridOptions } from 'ag-grid-community';
import { DatePipe } from '@angular/common';
import {ViewMoreButtonComponent} from "./view-more-button/view-more-button.component";


@Component({
  selector: 'app-report',
  templateUrl: './report.component.html',
  styleUrls: ['./report.component.scss']
})
export class ReportComponent implements OnInit {

  apiUrl: any;
  reports : Report[];
  gridOptions: GridOptions;
  dateValue = new Date();
  maxDate = new Date();
  private frameworkComponent;

  columnDefs = [
    {headerName: 'Report Name', field: 'reportName', resizable: true,
      valueGetter: params => { return `${params.data.reportName}.dat` }},
    {headerName: 'Sent to FIS', field: 'sentToFis',resizable: false,
      valueGetter: params => { return params.data.sentToXXX === true ? "Yes" : "No"  } },
    {headerName: 'File Size', field: 'contentLength', resizable: true,
      valueGetter: params => { return `${this.formatBytes(params.data.contentLength)}` }},
    {headerName: 'Last Modified', field: 'lastModified', resizable: true,
      valueGetter: params => { return this.datePipe.transform(params.data.lastModified, "yyyy-MM-dd HH:mm:ss") }},
    {headerName: '', field: 'value', resizable: false,
      cellRendererFramework: ViewMoreButtonComponent, width: 180, colId: 'params',
      valueGetter: params => {return `${params.data.id}`}}

  ];

  constructor(private reportService : ReportService, private datePipe: DatePipe) {
    this.frameworkComponent = {
      viewMoreButtonComponent: ViewMoreButtonComponent
    };
  }

  ngOnInit() {
    this.callReportService(new Date())

  }

  reportDateChange(value: Date) {

    let currentValue = this.datePipe.transform(this.dateValue, "yyyyMMdd")
    let newSelectedValue = this.datePipe.transform(value, "yyyyMMdd")
    if (currentValue != newSelectedValue) {
      if (this.gridOptions.api) {
        this.gridOptions.api.showLoadingOverlay();
      }
      this.callReportService(value)
      this.dateValue = value;
    }
  }

  callReportService(value: Date) {
    this.reportService.getReportsForDate(value).subscribe(x=> {
      this.reports = x;
      this.gridOptions.api.sizeColumnsToFit();

    })
  }

  ngAfterContentInit() {
    let agOpt = { ...{
      animateRows: true,
        enableRangeSelection: true,
        defaultColDef: {
          editable: false,
          enableValue: false,
          enableRowGroup: false,
          enablePivot: true,
          filter: true,
          sortable: true
        },
      statusBar: {
        statusPanels: [{
            statusPanel: 'agTotalRowCountComponent',
            align: 'left'
          },
          {
            statusPanel: 'agFilteredRowCountComponent'
          },
          {
            statusPanel: 'agSelectedRowCountComponent'
          },
          {
            statusPanel: 'agAggregationComponent'
          },
        ],
      }
     }, ...agThemeSgBootstrap }
    this.gridOptions  = { ...this.gridOptions, ...agOpt }
  }

  onGridReady(params) {
    params.api.setDomLayout("autoHeight");
    params.api.sizeColumnsToFit();
  }

  onGridSizeChanged(params) {
    params.api.sizeColumnsToFit();
  }

  ngAfterViewInit() {

    this.dateValue = new Date()


  }

  formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}


}

我的报表服务-(在get params函数的中间)

import { Injectable } from '@angular/core';
import { Report } from '../models/report';
import { HttpClient } from '@angular/common/http';
import { AppConfig } from '../app.config';
import { DatePipe } from '@angular/common'

@Injectable({
  providedIn: 'root'
})
export class ReportService {

  private apiUrl : string = ""
  private reportEndPoint : string = ""
  report: Report;
  constructor(private httpClient : HttpClient, private appConfig : AppConfig, public datePipe: DatePipe ) {
    this.apiUrl = this.appConfig.settings.apiServer.apiUrl;
    this.reportEndPoint = this.appConfig.settings.apiServer.reportEndPoint;
  }

  getReportsForDate(date : Date) {

     let transfomedDate = this.datePipe.transform(date, "yyyyMMdd")
     return this.httpClient.get<Report[]>(`${this.apiUrl}${this.reportEndPoint}${transfomedDate}` );

  }
  getParams() {
    return this.httpClient.get<Report[]>(`${this.apiUrl}${this.reportEndPoint}`);
    // this.report.reportName;
    // this.report.lastModified;
    // this.report.adlsFullPath;
    // this.report.contentLength;
    // this.report.creationDate;
    // this.report.sentToFis;
  }

 }



angular parameter-passing ag-grid
1个回答
0
投票

我的解决方案:我的孙子组件

import {Component, Input, OnInit} from '@angular/core';
import {Report} from "../../../../../models/report";
import {ReportService} from "../../../../../services/report.service";
import {ViewMoreButtonComponent} from "../view-more-button.component";
import {Router} from "@angular/router";

@Component({
  selector: 'app-view-more',
  templateUrl: './view-more.component.html',
  styleUrls: ['./view-more.component.scss']
})
export class ViewMoreComponent implements OnInit{

  public params: any;

  constructor(private router: Router, ) {
    this.params = this.router.getCurrentNavigation().extras.state;

  }

  ngOnInit(): void {
    // console.log(history.state);


    }

  }

我的孩子组成部分


import { Component, OnInit, Input } from '@angular/core';
import {ICellRendererAngularComp} from "@ag-grid-community/angular";
import {Report} from "../../../../models/report";
import {ViewMoreComponent} from "./view-more/view-more.component";
import {Router} from "@angular/router";

@Component({
  selector: 'app-view-more-button',
  templateUrl: './view-more-button.component.html',
  styleUrls: ['./view-more-button.component.scss'],
})
export class ViewMoreButtonComponent implements ICellRendererAngularComp {
  public params: any;
  reports: Report[];


  agInit(params: any) {
    this.params = params;
  }


  constructor(private router: Router) { }


  ngOnInit() {
  }

  refresh(): boolean {
    return true;
  }

  redirect() {
    this.router.navigateByUrl('/viewmore', {state:this.params.data})
  }

}

我的子组件html文件

<button class="viewMoreButton" mat-stroked-button (click)="redirect()">View More</button>
© www.soinside.com 2019 - 2024. All rights reserved.