首页 > 解决方案 > 如何在 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>

标签: javascripthtmlangularanchorviewchild

解决方案


如果需要调用一次,请在 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]);
        }
    );

推荐阅读