我想在点击两行之间显示一些自定义组件/ html。我相信快速简便的解决方案是使用点击处理程序中的事件并直接操作DOM,但是如果可能的话,我想以角度方式进行操作。
为了灵感,我首先看了this article扩展结构指令。它的用途有限,因为*matRowDef
不应该单独使用,而是与其他元素一起使用作为材料表的一部分。然后我去看看source code直接,并试图模仿MatRowDef
扩展CdkRowDef
的方式,并最终得到这个:
@Directive({
selector: '[expandableRowDef]',
providers: [
{provide: MatRowDef, useExisting: ExpandableRowDirective},
{provide: CdkRowDef, useExisting: ExpandableRowDirective}
],
inputs: ['columns: expandableRowDefColumns', 'when: expandableRowDefWhen']
})
export class ExpandableRowDirective<T> extends MatRowDef<T> {
constructor(template: TemplateRef<any>,
viewContainer: ViewContainerRef,
_differs: IterableDiffers) {
super(template, _differs);
}
}
然后我简单地用*matRowDef="..."
切换*expandableRowDef="..."
,它编译很好并且在运行时不会失败。
我应该从哪里开始编辑创建的mat-row
元素中的DOM?
我之前对类似的东西有一个基本的要求,并设法根据讨论把一些东西放在一起,并在this thread上破坏了plunkr。
它本质上是通过使用ComponentFactory
创建自定义组件,然后使用@ViewChildren
获取表行列表,然后单击选定的表行,使用index
在指定的@Input
中插入自定义组件传入行数据:
模板:
<mat-row *matRowDef="let row; columns: displayedColumns; let index = index"
(click)="insertComponent(index)"
#tableRow
matRipple>
</mat-row>
零件:
export class TableBasicExample {
displayedColumns = ['position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);
@ViewChildren('tableRow', { read: ViewContainerRef }) rowContainers;
expandedRow: number;
constructor(private resolver: ComponentFactoryResolver) { }
insertComponent(index: number) {
if (this.expandedRow != null) {
// clear old content
this.rowContainers.toArray()[this.expandedRow].clear();
}
if (this.expandedRow === index) {
this.expandedRow = null;
} else {
const container = this.rowContainers.toArray()[index];
const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(InlineMessageComponent);
const inlineComponent = container.createComponent(factory);
inlineComponent.instance.user = this.dataSource.data[index].name;
inlineComponent.instance.weight = this.dataSource.data[index].weight;
this.expandedRow = index;
}
}
}
插入行之间的自定义组件:
@Component({
selector: 'app-inline-message',
template: 'Name: {{ user }} | Progress {{ progress}}%',
styles: [`...`]
})
export class InlineMessageComponent {
@Input() user: string;
@Input() weight: string;
}
我在StackBlitz here上创建了一个基本的工作演示。由于此功能尚未得到官方支持,因此以这种方式执行此操作最终可能会破坏该行,但Angular Material团队确实具有类似in the pipeline的功能。