加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2:使用组件作为另一个组件的输入

发布时间:2020-12-17 17:34:47 所属栏目:安全 来源:网络整理
导读:我如何使用组件作为Angular中另一个组件的输入数据? 例如: 我想要bulid表组件AppTableComponent: app-table [dataSource]="dataSource" [columns]="columns" ng-container tableColumnDef="actions" a routerLink="/model/edit/{{item.id}}" routerLinkAc
我如何使用组件作为Angular中另一个组件的输入数据?

例如:

我想要bulid表组件AppTableComponent:

<app-table [dataSource]="dataSource" [columns]="columns">
  <ng-container tableColumnDef="actions">
    <a routerLink="/model/edit/{{item.id}}" routerLinkActive="active">Edit</a>
    <a routerLink="/model/delete/{{item.id}}" routerLinkActive="active">Delete</a>
  </ng-container>
  <ng-container tableColumnDef="isActive">
    <div [ngClass]="{cercl:true,'is-active':item.is_active}">&nbsp;</div>
  </ng-container>
</app-table>

dataSource是数据数组,如Model []或Person []或Car []. columns是一个字符串数组,如[‘id’,’isActive’,’name’,’actions’].它应该包含dataSource行的名称或附加列名称.

我知道如何使用ng-content,但这不是一个很小的例子.区别是我应该在一些地方使用部分内容.也许我应该使用ng-contet,但我不知道什么.

我确信我的目标是可行的,因为Angular材料表的工作如下:

<mat-table #table [dataSource]="dataSource">
    <ng-container matColumnDef="position"></ng-container>
    <ng-container matColumnDef="weight"></ng-container>
</mat-table>

请不要建议我使用Angular材料表组件.我不需要桌子.我只想学习一些新东西.

我会对任何有关主题的信息或文章感到满意!

解决方法

如果要在使用者部件上管理模板,则必须使用Angular嵌入式视图(ng-template).这就是材料在其表实现中使用的内容.

<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

你可以说没有任何嵌入式视图,但让我们看看上面模板的扩展版本:

<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="position">
    <ng-template matHeaderCellDef>
      <th mat-header-cell> No. </th>
    </ng-template>
    <ng-template matCellDef let-element="$implicit">
      <td mat-cell> {{element.position}} </td>
    </ng-template>
  </ng-container>

我们可以注意到< ng-template matHeaderCellDef>这里可以通过使用ContentChild获得.

Angular材料团队为此类模板创建专用指令https://github.com/angular/material2/blob/f2c7205d6608d36a2016d90090be2a78d4f3233e/src/lib/table/cell.ts#L32,该模板保留对嵌入式模板https://github.com/angular/material2/blob/676ce3b285718d2ee19ad6ae5702917566167641/src/cdk/table/cell.ts#L34的引用

材料表组件具有以下模板:

<ng-container headerRowOutlet></ng-container>
<ng-container rowOutlet></ng-container>
<ng-container footerRowOutlet></ng-container>

还有指令 – 助手,如:

@Directive({selector: '[headerRowOutlet]'})
export class HeaderRowOutlet implements RowOutlet {
  constructor(public viewContainer: ViewContainerRef,public elementRef: ElementRef) { }
}

这样我们就可以使用低级api来创建基于嵌入式模板的元素,例如ViewContainerRef.createEmbeddedView(templateRef),但是可以在这里找到简单的实现:

> How to render multiple ng-content inside an ngFor loop using Angular 4?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读