我试图访问结构指令中的“子”指令,以便在该指令中注入一些数据。但这总是导致未定义或注入错误。
我有以下html:
<app-table [dataSource]="data">
<button *customColumn="let row" [highlightRowOnClick]="row">
click here!
</button>
</app-table>我希望通过customColumn将所有行注入到[highlightRowOnClick]指令中,这样它就可以在单击当前行时取消选择所有其他行。
如何将所有行传递给指令:(app-table -> *customColumn -> [highlightRowOnClick])。
我已经创建了一个斯塔克布利茨,在行选择工作的情况下再现这个问题,但没有行取消选择。
My Toughts
@ContentChildren访问子组件,因为[highlightRowOnClick]指令不是直接子组件,而是视图中的同级组件(更多在这里)。@Host装饰器),但是这并不是完全正确的。这将导致注入器错误(no provider for 'customColumn' found)。(这里描述了这一点)[highlightRowOnClick]指令中,但这需要程序员每次都这样做。在我看来,您只想突出显示当前行是有意义的,而且我也不想将所有行都暴露给该位置上的程序员,因为程序员已经可以通过[dataSouce]访问它们。所以我认为这不是最好的解决办法。示例:
<app-table [dataSource]="rows">
<button *customColumn="let row; let rows=rows" [highlightRowOnClick]="row" allRows="rows">
click here!
</button>
</app-table>有谁知道我有更好的办法解决这个问题吗?还是用完全不同的方法?
发布于 2019-08-09 07:48:35
就像包装器组件中的所有内容一样,可以将其注入HighlightRowOnClickDirective中。
constructor(@Optional() @Host() private wrap:WrapperComponent ){}
@Input('highlightRowOnClick')
row: Row;
@HostListener('click')
onClick(): void {
this.wrap.dataSource.forEach(x=>{
x.isSelected=(x==this.row)
})
}
}请参阅stackblitz
但实际上,我不知道为什么不使用变量"indexSelected“,使用*ngFor="...;let i=index"和传递作为参数
使用索引选择更新。
我们可以在行"isSelected“中有一个变量,或者在包装器"indexSelected”中有一个唯一的变量,并将索引作为值传递。
<div *ngFor="let row of dataSource;let i=index">
<div [class.selected]="i==indexSelected"> Hello world! </div>
<ng-container *ngFor="let col of colHeaders">
<ng-template *ngTemplateOutlet="col.template; context: { $implicit: i }"></ng-template>
</ng-container>
<br><br>
</div>指令变成
@Input('highlightRowOnClick')index:number
@HostListener('click')
onClick(): void {
this.wrap.indexSelected=this.index
}请参阅又一次堆栈闪电战
https://stackoverflow.com/questions/57424798
复制相似问题