javascript - 如何在 Angular 2+ 中更改锚点的 html 元素后设置 @ViewChild('anchor_name')?
问题描述
我得到一个带有 GET 请求的项目,然后在订阅时设置 item_id。在 html 中,我使用锚 id="{{this.item_id}}" 制作 div。之后我得到错误:
FeedComponent.html:1 ERROR TypeError: Cannot read property 'nativeElement' of undefined
我知道当构造函数检查 html 元素时,这个带有这个锚点的元素是不存在的。但我不知道如何在订阅 GET 请求时使用 @ViewChild 设置 uncor?
有组件:
export class MyClass {
@ViewChild('10') private myScrollContainer: ElementRef;
item_id = 0;
constructor (scrollChecker: ScrollChecker) {
this.getItem();
}
getItem(){
// get request there
.subscribe((p) => {
this.item_id = p.id;
});
}
doScrollToItem(){
this.viewportScroller.scrollToPosition([0,this.myScrollContainer.nativeElement.offsetTop]);
}
}
的HTML:
<div *ngIf="item_id" id="{{item_id}}"></div>
解决方案
如果需要调用一次,请在 setter 中调用滚动条:如果要设置 Id,请从 setter 内部调用 getItem。这样, _myContainer 将在调用订阅时设置
const _myContainer: ElementRef
@ViewChild('10') set myScrollContainer(element: ElementRef) {
if(element && element.nativeElement) {
_myContainer = element;
this.getItem()
}
}
getItem(){
// get request there
.subscribe((p) => {
this.item_id = p.id;
//set your id using angular renderer2
this.renderer.setAttribute(this._myContainer, 'id', p.id)
});
}
constructor (scrollChecker: ScrollChecker, private renderer: Renderer2) {
}
否则只需在 doScrollToItem() 内滚动之前检查 this.myScrollContainer.nativeElement 是否未定义:
doScrollToItem(){
if(this.myScrollContainer && this.myScrollContainer.nativeElement) {
this.viewportScroller.scrollToPosition([0,this.myScrollContainer.nativeElement.offsetTop]);
}
);
推荐阅读
- c# - 将 Json 数据绑定到 Echart
- javascript - 使用 JavaScript 在 2 个不同的数组中查找不重复项的数量?
- angular - Angular 模板驱动的自定义验证器
- css - Css 网格 - html 表单 - 我无法在垂直流中引导我的元素
- sql - 更新 SQL 查询本身死锁
- java - 如何为 TableView 创建条件 CellValueFactory?
- vim - 如何映射键“;” 在尼奥维姆
- php - 返回或回显视图有什么区别?返回视图说话的时间比回声视图长
- android - 检查权限的自定义方法
- angular - 传单 Property-Routing-does-not-exist-on-type-typeof-import