如何访问使用 NgFor 创建的元素
How can I get access to elements created with NgFor
大家早上好。我以前问过这个问题但没有答案,但我的问题措辞不当所以 I've put together a plunk that will hopefully show what I'm doing
尽可能简单 - 我有一个 Service
,它提供了当前选择的名称和曲目的列表。它还具有更改此选择的方法和一个 BehaviourSubject
通知何时发生更改。当前选择的名称显示在主应用程序中。
完整的名称列表由 Component
显示,另一个 Component
提供 UI 用于更改所选名称。
When the selection changes, this is reflected both in the main app and by the position of the ListComponent
which will always have the selected name aligned with the left of the screen.
我的问题是关于我在定位和设计 ListComp
时使用的方法。这些在 src/list.com.ts
中的第 40 行开始 my plnk.
当组件收到所选项目已更改的通知时,我需要获取对 ngFor
基于该数据项创建的特定 HTMLElement 的引用。然后,我需要将样式应用到所选元素并移动容器,使其与布局的其余部分对齐。
定位部分 有效 正如你可以看到使用 getElementById()
但是有更多的 Angular 方式可以吗?
然后我完全不确定将 selected
样式应用到当前选定元素的最佳方法。任何和所有的建议都很好!
我真的希望这是有道理的。我在原始版本上花费了太长时间,现在在 plnkr 和 SO 上,我希望我只是错过了树木(或其他东西)的木材。
如果我的解释有任何问题,请大声说出来。
非常感谢大家:)
我可能不完全理解您的问题,但我会建议您不需要访问元素而是更新模型并让 Angular 进行 DOM 修改的方法:
<div *ngFor="let item of listService.listData" class="cell" id="cell-{{item}}"
[class.selected]="item == selected">{{item}}</div>
constructor(private listService:ListService){
accordingly
listService.nameSelection.subscribe(name => {
this.selected = name;
});
}
大家早上好。我以前问过这个问题但没有答案,但我的问题措辞不当所以 I've put together a plunk that will hopefully show what I'm doing
尽可能简单 - 我有一个 Service
,它提供了当前选择的名称和曲目的列表。它还具有更改此选择的方法和一个 BehaviourSubject
通知何时发生更改。当前选择的名称显示在主应用程序中。
完整的名称列表由 Component
显示,另一个 Component
提供 UI 用于更改所选名称。
When the selection changes, this is reflected both in the main app and by the position of the ListComponent
which will always have the selected name aligned with the left of the screen.
我的问题是关于我在定位和设计 ListComp
时使用的方法。这些在 src/list.com.ts
中的第 40 行开始 my plnk.
当组件收到所选项目已更改的通知时,我需要获取对 ngFor
基于该数据项创建的特定 HTMLElement 的引用。然后,我需要将样式应用到所选元素并移动容器,使其与布局的其余部分对齐。
定位部分 有效 正如你可以看到使用 getElementById()
但是有更多的 Angular 方式可以吗?
然后我完全不确定将 selected
样式应用到当前选定元素的最佳方法。任何和所有的建议都很好!
我真的希望这是有道理的。我在原始版本上花费了太长时间,现在在 plnkr 和 SO 上,我希望我只是错过了树木(或其他东西)的木材。
如果我的解释有任何问题,请大声说出来。
非常感谢大家:)
我可能不完全理解您的问题,但我会建议您不需要访问元素而是更新模型并让 Angular 进行 DOM 修改的方法:
<div *ngFor="let item of listService.listData" class="cell" id="cell-{{item}}"
[class.selected]="item == selected">{{item}}</div>
constructor(private listService:ListService){
accordingly
listService.nameSelection.subscribe(name => {
this.selected = name;
});
}