@ViewChild无法提供ElementRef,可以找出原因吗?

时间:2017-10-24 09:58:43

标签: angular

我正在尝试访问elementRef,但是有些东西失败了, 我知道如果有一些rending条件(* ngif)是错误的,并且视图不存在的问题,那么你就无法获得elementRef,这对应用程序启动时是正确的,但是我已经尝试在它被绘制之后很久才访问它。

HTML:

<div (click)="activateGroupDropdown()" class="group-name"><div class="title">Choose Site<i class="fa fa-angle-down" aria-hidden="true"></i></div>
    <div #groupDropdown class="dropdown" [ngClass]="{'active': isGroupDropDown}">
        <ul [ngClass]="{'active': isGroupDropDown}">
            <li>Sparta</li>
            <li>Athene</li>
            <li >Vilnius</li>
            <li #liButtons class="action-btns">
                <button>cancel</button><button class="success">ok</button>
            </li>
        </ul>
    </div>
</div>

TS:

export class CameraScreensOptionsComponent implements OnInit, OnDestroy {

    @ViewChild('groupDropdown') elGroupDropdown: ElementRef;
    @ViewChild('liButtons') elLastListItem: ElementRef;
    afterDropdownTransition(event) {
        console.log('transition ended!');
        if ( !this.isGroupDropDown ) {
             console.log('here!', this.elGroupDropdown );
             this.elGroupDropdown.nativeElement.style.visibility = 'hidden';
        }
    }
    activateGroupDropdown() {
        this.isGroupDropDown = !this.isGroupDropDown;
        console.log('toggling the site grouping drop down');
    }
    initGrouping() {
        this.isGroupingInitiated = true;
       // moving the action to the end of the queue
       // so that angular would have time to draw view
       // before I put event listener on elLastListItem
       setTimeout( _ => this.elLastListItem.nativeElement.addEventListener('transitionend', this.afterDropdownTransition), 0);
       console.log('initiating grouping options display');
   }   
}

1 个答案:

答案 0 :(得分:1)

使用addEventListener时,您应该更加专注:

.addEventListener('transitionend', this.afterDropdownTransition)
                                       ^^^^^^^^^^^^^^^^^
                                    you will lose the context here

快速修复正在添加.bind(this)

.addEventListener('transitionend', this.afterDropdownTransition.bind(this))

上述代码可帮助我们在this函数中保留afterDropdownTransition。它将引用组件实例。

有关其他解决方案,请参阅