结构指令获取子指令

Structural directive get child directive

我正在尝试访问结构指令中的 'child' 指令,以便我可以在该指令中注入一些数据。但这总是导致未定义或注入错误。

我有以下 html:

<app-table [dataSource]="data">
  <button *customColumn="let row" [highlightRowOnClick]="row">
    click here!
  </button>
</app-table>

我想通过 customColumn 将所有行注入到 [highlightRowOnClick] 指令中,这样它就可以删除 select 单击当前行时的所有其他行

我想如何将所有行传递给指令: (app-table --> *customColumn --> [highlightRowOnClick])。

我已经创建了一个 Stackblitz 重现此问题,行 selection 有效,但行 deselection 无效。


我的心得

示例:

<app-table [dataSource]="rows">
  <button *customColumn="let row; let rows=rows" [highlightRowOnClick]="row" allRows="rows">
    click here!
  </button>
</app-table>

有谁知道解决这个问题的更好方法吗?或者也许是一种完全不同的方法?

由于包装器组件中包含所有内容,因此您可以将其注入 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" 并作为参数传递

更新 使用索引 Select。

我们可以在行 "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
  }

another stackblitz