我正在使用 angular (^8.2.14) 和 ag-grid-community (^20.1.0)。
我尝试达到以下效果:当用户悬停特定行时,一列显示一个可以单击的附加按钮。
有什么作用?
具有所需行为的列由实现 ICellRendererAngularComponent 的自定义单元格渲染器组件渲染。界面。在那里我可以注入(inject) ElementRef 和生命周期 Hook AfterContentChecked我检查 parent 的 parent 是否有 css-class 'ag-row-hover',如果它在那里,我将在渲染器组件中显示这个额外的按钮。
自定义cell.component.ts
@Component({
selector: 'app-custom-cell',
template: `
<ng-container *ngIf="hovered; else notHovered">{{form.value * form.value}}
<button (click)="doStuff(form.value)">show root</button></ng-container>
<ng-template #notHovered>{{form.value + form.value}}</ng-template>
`,
})
export class CustomCellComponent implements ICellRendererAngularComp, AfterContentChecked {
form: FormControl;
params: ICellRendererParams;
hovered = false;
constructor(private elementRef: ElementRef) {
}
doStuff(val) {
alert(val);
}
ngAfterContentChecked() {
this.hovered = (this.elementRef.nativeElement as HTMLElement)
.parentElement
.parentElement
.classList.contains('ag-row-hover');
}
}
源代码位于 github
我想改进什么?
我想提高性能,而不是对这种行为进行明确的检查。我宁愿有一个带有 css-selector '.ag-row' 的指令,我可以将它注入(inject)到 ICellRendererAngularComponent 中,然后在每次检查时检查 css 类 '.ag-row-hover'。或者有一个带有 css-selector '.ag-row-hover' 的指令,它存在或不存在。有人对如何改进我现有的解决方案有任何想法吗?
最佳答案
您实际上可以仅使用 CSS 实现所需的行为,无需注入(inject) ElementRef 或通过 Angular Lifecycle Callbacks 执行任何操作。
话虽如此,您的自定义渲染器可能看起来像这样:
@Component({
selector: "app-custom-cell",
template: `
<span style="color: red;">
<div class="visible-on-hover">
{{ form.value * form.value }}
<button (click)="doStuff(form.value)">show root</button>
</div>
<div class="hidden-on-hover">{{ form.value + form.value }}</div>
</span>
`
})
export class CustomCellComponent
implements ICellRendererAngularComp {
form: FormControl;
params: ICellRendererParams;
constructor() {}
doStuff(val) {
alert(val);
}
//... other stuff
}
在你的 styles.scss (或者更适合的地方,只是 make sure the styles apply ),只需添加这些规则:
div.visible-on-hover {
display: none;
}
.ag-row-hover {
div.visible-on-hover {
display: block;
}
div.hidden-on-hover {
display: none;
}
}
从概念上讲,浏览器渲染引擎会执行您在 ngAfterContentChecked() 中所做的事情。
关于css - 当行悬停在 ag-grid 中时,在单元格中呈现附加信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59695381/