首页 > 解决方案 > 如何以角度动态创建 n 级嵌套展开/折叠组件

问题描述

我正在使用 div 开发 n 级嵌套表的脚本。

所以有 5 到 6 列n的行数,每一列都必须展开/折叠按钮,单击该按钮我会调用 API,它会为我提供与所选行过滤器相关的数据。

以前当我使用核心 JavaScript 和 jQuery 时,我使用文档选择器的方法来识别展开/折叠按钮的父级,并仅使用jQuery 的或方法find在特定 div 之后推送动态创建的 HTMLinnerHTMLappend

我对角度有点陌生,而且工作不多。请帮我解决这个问题。

splitOpt是一个对象数组,我将根据这些对象拆分报告数据。

this.splitOpt = [
    {
        id: "country",
        label: "Country"
    },
    {
        id:"os".
        label:"Operating System"
    },
    {
        id:"osv".
        label:"Operating System Version"
    }
]

获取报告的功能

getReport() {

    // apiFilters are array of object having some values to filter report data  
    var apiFilters: any = [{}];
    for (var i = 0; i < this.sFilters.length; i++) {

        if (this.sFilters[i][0].values.length > 0) {
            var k;
            k = this.sFilters[i][0].id
            apiFilters[0][k] = this.sFilters[i][0].values;
        }
    }

    var split = this.splitOpt[0].id;
    this._apis.getReportData(split, apiFilters[0]).subscribe(response => {
        if (response.status == 1200) {
            this.reportData = response.data.split_by_data;
        }
    })
}

检查是否有更多拆分的功能

checkIfHaveMoreSplits(c){
      if(this.splitOpt.length > 0) {
        var index = this.splitOpt.findIndex(function(v) {
          return v.id == c
        })

       if (typeof(this.splitOpt[index+1]) != "undefined"){
         return this.splitOpt[index+1];
       } else {
        return 0;
       }
   }

    }

基于拆分和报告数据绘制表格的代码。

假设对象中的国家/地区只有一个对象而splitopt不是checkIfHaveMoreSplits()返回0,这意味着我不必提供展开按钮,如果不是0,则展开按钮将出现在那里。

单击展开按钮,我将从中选择下一个元素splitopt并调用 API 以获取具有拆分参数作为载体的报告,依此类推。

<div class="table" >
<div class="row" *ngFor="let rData of reportData; let i = index;" >
        <div class="col" >

            <button 
                 class="btn btn-sm" 
                 *ngIf="checkIfHaveMoreSplits(splitbykey) !== 0"
                 (click)="splitData(splitbykey)"
                >+</button>
            {{rData[splitbykey]}}
        </div>
        <div class="col">{{rData.wins}}</div>
        <div class="col">{{rData.conversions}}</div>
        <div class="col">{{rData.cost}}</div>
        <div class="col">{{rData.bids}}</div>
        <div class="col">{{rData.impressions}}</div>
        <div class="col">{{rData.rev_payout}}</div>

</div>

我正在管理一个数组,该数组确定我可以展开折叠元素的深度

让我们假设数组具有三个元素,即国家、运营商和操作系统

因此,我将绘制的第一个表格包含表格中的所有国家,点击展开按钮,我将发送所选国家并获取该特定国家的运营商。获得响应后,我想根据响应创建自定义 HTML,并在选定行后附加 html。

以下是屏幕截图以及完整的工作流程:)

步骤1在此处输入图像描述

第2步

在此处输入图像描述

第 3 步

在此处输入图像描述

标签: javascripthtmlangularangular5

解决方案


我建议为您要显示的每个动态 HTML 片段编写一个自定义角度组件。然后,您可以编写一个循环组件,该组件将*ngIf根据您提供的类型列表来嵌套组件。像这样:

// dynamic.component.ts

export type DynamicComponentType = 'country' | 'os' | 'osv';
export interface IOptions { /* whatever options you need for your components */ }
export type DynamicComponentOptions = { type: DynamicComponentType, options: IOptions};

@Component({
  selector: 'app-dynamic',
  template = `
    <app-country *ngIf="current.type == 'country'" [options]="current.options" />
    <app-os *ngIf="current.type == 'os'" [options]="current.options" />
    <app-osv *ngIf="current.type == 'osv'" [options]="current.options" />
    <ng-container *ngIf="!!subTypes"> 
      <button (click)="dynamicSubComponentShow = !dynamicSubComponentShow" value="+" />
      <app-dynamic *ngIf="dynamicSubComponentShow" [options]="subOptions" />
    </ng-container>`,
  // other config
})
export class DynamicComponent {

  @Input() options: DynamicComponentOptions[];

  get current(): DynamicComponentOptions { 
    return this.options && this.options.length && this.options[0]; 
  }
  get subOptions(): DynamicComponentOptions[] {
    return this.options && this.options.length && this.options.slice(1);
  }

  dynamicSubComponentShow = false;

  // component logic, other inputs, whatever else you need to pass on to the specific components
}

的示例CountryComponent。其他组件看起来相似。

// country.component.ts

@Component({
  selector: 'app-country',
  template: `
    <div>Country label</div>
    <p>Any other HTML for the country component using the `data` observable i.e.</p>
    <span>x: {{ (data$ | async)?.x }}</span>
    <span>y: {{ (data$ | async)?.y }}</span>
  `,
})
export class CountryComponent {

  @Input() options: IOptions;

  data$: Observable<{x: string, y: number}>;

  constructor(private countryService: CountryService) {
    // load data specific for this country based on the input options
    // or use it directly if it already has all your data
    this.data$ = countryService.getCountryData(this.options);
  }
}
// my.component.ts

@Component({
  template: `
    <div class="table" >
      <div class="row" *ngFor="let rData of reportData$ | async; let i = index;" >
        <div class="col" >
          <app-dynamic [options]="options$ | async"></app-dynamic>
        </div>
        ...
      </div>
    </div>`,
  // other cmp config
})
export class MyComponent {

  options$: Observable<DynamicComponentOptions[]>;
  reportData$: Observable<ReportData>;

  constructor(private reportService: ReportService){

    // simplified version of your filter calculation
    let apiFilters: {} = this.sFilters
      .map(f => f[0])
      .filter(f => f && f.values && f.values.length)
      .reduce((f, acc) => acc[f.id] = f.values && acc, {});

    this.reportData$ = reportService.getReportData(this.splitOpt[0].id, apiFilters).pipe(
      filter(r => r.status == 1200),
      map(r => r.data.split_by_data)
    );
    this.options$ = this.reportData$.pipe(map(d => d.YOUR_OPTIONS));
  }
}

现在让你的 api 返回类似

{
  "status": 1200,
  "data": {
    "YOUR_OPTIONS": [{
      "type": "country"
      "options" { "id": 1, ... } // options for your country component initialization
    }, {
      "type": "os",
      "options" { "id": 11, ... } // options for your os component initialization
    }, ...],
    // your other report data for the main grid
  }
}

请根据您的特定需求进行调整。例如,您必须管理通过组件层次结构的状态传递(使用组件状态、可观察服务、MobX、NgRx - 选择你的毒药)。

希望这有所帮助 :-)


推荐阅读