动态如何在单击的表单元格中创建组件
some.component.html
<table>
<tr *ngfor="let row in table">
<td *ngFor="let cell in row" (click)="onCellClick($event)">Cell Text</td>
</tr>
</table>
@Component({
selector: 'app-my-component',
template: '<div>My Component</div>',
})
export class MyComponent { }
@Component({
selector: 'app-some',
templateUrl: './some.component.html'
})
export class SomeComponent {
public table = [[1, 2, 3], [4, 5, 6]];
constructor(
private viewContainerRef: ViewContainerRef
) { }
onCellClick(event: MouseEvent): void {
const myComponent = this.viewContainerRef.createComponent(MyComponent);
}
}
此代码在&lt;/table&gt;
之后添加myComponent。但是我需要在单击的表单元格中创建myComponent(内部td
)。我该怎么做?
some.component.html
<table>
<tr *ngfor="let row in table">
<td *ngFor="let cell in row" (click)="onCellClick($event)">Cell Text</td>
</tr>
</table>
@Component({
selector: 'app-my-component',
template: '<div>My Component</div>',
})
export class MyComponent { }
@Component({
selector: 'app-some',
templateUrl: './some.component.html'
})
export class SomeComponent {
public table = [[1, 2, 3], [4, 5, 6]];
constructor(
private viewContainerRef: ViewContainerRef
) { }
onCellClick(event: MouseEvent): void {
const myComponent = this.viewContainerRef.createComponent(MyComponent);
}
}
This code adds MyComponent after </table>
. But I need MyComponent to be created inside of the clicked table cell (inside td
). How can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注意:此无工厂版本仅在每行中都有相同数量的单元格(因为我们使用CellsPerrow来猜测单元格的索引):
好的,首先导入所有我们需要的东西:
添加ViewChildren Decorator在构造函数下方以获取所有单元格的元素:
添加一个cellperrow常数:
然后像这样修改您的oncellClick:
最后,更改HTML以将当前单元格的索引传递到OnCellClick()(并添加未来组件的容器,#cellelem,#cellelem,#cellelem,#cellelem, TD Elem):
Note: This factory-less version only works if you have the same number of cells in every row (since we're using cellsPerRow to guess the index of the cell) :
Alright, first import everything we'll need :
Add a ViewChildren decorator below your constructor to get all the cells elems :
Add a cellsPerRow constant :
Then modify your onCellClick like so :
Finally, change the HTML to pass the current cell's index to onCellClick() (and add the future component's container, #cellElem, inside your td elem) :