Angular 4 可重用组件和模板

6
我是一个有用的助手,可以将文本翻译成中文。
我在创建Angular 4中可重复使用组件方面遇到了困难。我有一堆报表,每个报表都包含一个搜索表单(每个报表的字段不同)和一个材料表格结果列表(每个报表的字段列表不同)。当我为每个报表复制整个组件时,它按预期工作,但我想将其重构为可重用的组件/模板和子组件来扩展它。但作用域都错了,我无法理解这是如何工作的。
report.component.ts(可重用组件)
import {Component, ViewChild} from '@angular/core';
import {MatPaginator} from '@angular/material';

import 'rxjs/add/operator/map';

import {ReportsDataSource} from '../services/reports-datasource.service';

@Component({
    selector: 'app-report',
    templateUrl: './report.component.html',
})
export class ReportComponent {
    @ViewChild(MatPaginator) paginator: MatPaginator;

    /** result table columns */
    columns = [];

    /** Column definitions in order */
    displayedColumns = this.columns.map(x => x.columnDef);

    /** empty search parameters object, used for form field binding */

    /** datasource service */
    dataSource: ReportsDataSource;

    /** submit the form */
    getData() {
        this.dataSource.getData();
    }
}

report.component.html(可重复使用的模板)

<form (ngSubmit)="getData()" #ReportSearchForm="ngForm">
    <ng-content select=".container-fluid"></ng-content>
    <button type="submit" mat-button class="mat-primary" [disabled]="!ReportSearchForm.form.valid">Search</button>
</form>
<mat-table #table [dataSource]="dataSource">
    <ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
        <mat-header-cell *matHeaderCellDef>{{ column.header }}</mat-header-cell>
        <mat-cell *matCellDef="let row">{{ column.cell(row) }}</mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator #paginator
               [length]="dataSource ? dataSource.meta.total_results : 0"
               [pageSize]="dataSource ? dataSource.meta.per_page : 25"
               [pageSizeOptions]="[10, 25, 50, 100]"
>
</mat-paginator>

childreport.component.ts (a specific report)

import {Component, OnInit} from '@angular/core';

import {ReportComponent} from '../report.component';
import {ChildreportService} from './childreport.service';
import {ReportsDataSource} from '../../services/reports-datasource.service';

@Component({
    selector: 'app-report-child',
    templateUrl: './childreport.component.html',
    providers: [ChildreportService, ReportsDataSource]
})
export class ChildreportComponent extends ReportComponent implements OnInit {
    constructor(private childreportService: ChildreportService) {
        super();
    }

    /** result table columns */
    columns = [
        {columnDef: 'column1', header: 'Label 1', cell: (row) => `${row.column1}`},
        {columnDef: 'column2', header: 'Label 2', cell: (row) => `${row.column2}`}
    ];

    ngOnInit() {
        this.dataSource = new ReportsDataSource(this.ChildreportService, this.paginator);
    }
}

childreport.component.html(在父模板中嵌入的此报告的搜索表单)

<app-report>
    <div class="container-fluid">
        <mat-form-field>
            <input matInput placeholder="some field" name="fieldx">
        </mat-form-field>
    </div>
</app-report>

可以正常工作的是,我已经将表单嵌入到主模板中,并且没有出现任何错误。

不正常工作的是,表单和表格绑定到了ReportComponent而不是ChildreportComponent。我有点理解为什么会发生这种情况(因为此模板的范围是该组件),但我不知道如何"继承"该模板并处于ChildreportComponent的范围内。我漏掉了什么?

2个回答

4
我自己想出了解决方法。实际上,解决方案相当简单。我的错误在于在报告组件中尝试同时提供模板和逻辑。我最终得到的是一个抽象组件,它保存了逻辑,并由每个报告进行扩展,以及几个较小的组件,用于每个报告中的类似部分(外壳、结果列表等)。我还从模板表单切换到响应式表单。

report-base.component.ts保存公共逻辑

import {OnInit} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {MatPaginator, MatSidenav} from '@angular/material';

import 'rxjs/add/operator/map';

import {ReportsDataSource} from '../common/services/reports-datasource.service';
import {ReportsService} from '../common/services/reports.service';
import {ReportsResultlistService} from '../common/services/reports-resultlist.service';

export abstract class ReportBaseComponent implements OnInit {
    constructor(
        protected _formBuilder: FormBuilder, protected _reportService: ReportsService, protected _resultlistService: ReportsResultlistService) {
    }


    /**
     * For toggling the search form and resultlist action buttons
     * @type {boolean}
     */
    protected hasResults = false;

    /** Default data source for the table */
    protected dataSource: ReportsDataSource;

    /** search form controls */
    protected searchForm: FormGroup;

    /** result table columns */
    protected columns = [];

    ngOnInit() {
        this.createForm();
        this.dataSource = new ReportsDataSource(this._reportService, this._resultlistService);
    }

    /**
     * Builds the searchForm Group
     */
    protected createForm() {
        // create an empty form
        this.searchForm = this._formBuilder.group({});
    }

    /**
     * Submits the form/loads data (f.ex. pagination)
     */
    protected getData() {
        this.hasResults = true;
        this.dataSource.search = this.searchForm.value;
        this.dataSource.getData();
    }
}

report-shell.component.ts 是一个子组件(这是我的逻辑错误之一),为其他组件提供外壳:

import {Component, Input} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
    selector: 'app-report-shell',
    templateUrl: './report-shell.component.html',
})
export class ReportShellComponent {
    constructor(private route: ActivatedRoute) {
        this.title = route.routeConfig.data['caption'];
    }

    @Input() hasResults = false;
    title: string;
}

report-shell.component.html 提供搜索表单和结果列表的 HTML 框架。

<mat-expansion-panel [expanded]="!hasResults">
    <mat-expansion-panel-header>
        Search
    </mat-expansion-panel-header>
    <ng-content select="form"></ng-content>
</mat-expansion-panel>
<div class="result-list">
    <mat-toolbar class="result-header"><span>{{ title }}</span>
        <span class="fill-remaining-space"></span>
        <button class="fa fa-file-excel-o" (click)="exportExcel()"></button>
    </mat-toolbar>
    <ng-content select=".result-table"></ng-content>
</div>

所以我的报告扩展了报告基础,并简单地将shell作为子级使用:

childreport.component.ts 是一个特定的报告,只实现了针对此报告的特定内容。

import {Component, OnInit} from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';

import {ReportChildreportService} from './childreport.service';
import {ReportsDataSource} from '../../common/services/reports-datasource.service';
import {ReportsResultlistService} from '../../common/services/reports-resultlist.service';

import {ReportBaseComponent} from '../report-base.component';


@Component({
    selector: 'app-report-dispatches',
    templateUrl: './dispatches.component.html',
    providers: [ReportChildreportService, ReportsResultlistService, ReportsDataSource]
})
export class ReportDispatchesComponent extends ReportBaseComponent implements OnInit {
    constructor(protected _reportService: ReportChildreportService, protected _formBuilder: FormBuilder, protected _resultlistService: ReportsResultlistService) {
        super(_formBuilder, _reportService, _resultlistService);
    }

    /** result table columns */
    columns = [
        {columnDef: 'name', header: 'Name', cell: (row) => `${row.name}`}
    ];

    createForm() {
        this.searchForm = this._formBuilder.group({
            name: ''
        });
    }
}

childreport.component.html

<app-report-shell [hasResults]="hasResults">
    <form (ngSubmit)="getData()" [formGroup]="searchForm" novalidate>
                    <mat-form-field>
                        <input matInput placeholder="search for a name" name="name" formControlName="name">
                        <mat-error>Invalid name</mat-error>
                    </mat-form-field>
                </div>
        </div>
        <app-form-buttons [status]="searchForm.status"></app-form-buttons>
    </form>
        <app-report-result-list
                [(dataSource)]="dataSource"
                [columns]="columns"
                [displayedColumns]="displayedColumns"
                class="result-table"
        ></app-report-result-list>    
</app-report-shell>

我不会详细介绍表单和结果列表组件,因为这个答案已经够长了 :-)

所以我成功地大大减少了代码重复,尽管仍然有一些(除了表单之外,所有内容都在childreport.component.html中)。


0

我建议你看一下这篇文章。@WjComponent装饰器可能会给你提供一些关于你的方法的线索。 从文章中我理解的是,你需要一个新的组件装饰器来在基类和子类之间共享属性。

文章引用:

@Component({  selector: 'inherited-grid'
})
export class InheritedGrid extends wjGrid.WjFlexGrid {
...
}

现在我们有了组件的新元素名称!但是,我们错过了在基本WjFlexGrid类的装饰器中定义的所有其他必要设置。例如,WjFlexGrid的装饰器将输入装饰器属性分配给可在标记中绑定的网格属性数组。我们在新组件中丢失了它,如果您现在尝试将其绑定,您会发现绑定不起作用。
答案:由Wijmo for Angular 2模块提供的@WjComponent装饰器。它的使用方式与标准的@Component装饰器相同,并接受所有@Component装饰器的属性(加上一些特定于Wijmo的属性),但它的主要优点是将其属性值与基类装饰器提供的属性合并。因此,我们组件定义的最后一步是将@Component替换为@WjComponent: import { WjComponent } from 'wijmo/wijmo.angular2.directiveBase';
@WjComponent({
  selector: 'inherited-grid'
})
export class InheritedGrid extends wjGrid.WjFlexGrid {
...
}

我们可能已经重新定义了装饰器的选择器属性,使用了“inherited-grid”这个名称,但是所有其他必要的属性,比如输入和输出,都是从基础的WjFlexGrid组件的装饰器中获取的。现在,元素创建了我们的InheritedGrid组件,并且所有的属性和事件绑定都能正常工作!
另一种方法可能是将ReportComponent定义为指令,并通过@Host装饰器在ChildReport和基础之间共享数据。
您也可以查看ngx-datatable的源代码。他们的示例和组件的源代码非常有信息量,可能会给您关于在组件之间共享数据和覆盖模板方面提供灵感。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接