当我尝试读取滚动时的 nativeElement 时出现错误。NativeElement 是未定义的,尽管我实现了 AfterViewInit。我还在我的 H1 中将一个引用变量与 viewchild 一起使用。
问题出在 myDiv viewchild 上。另外,在我的模板中,我添加了引用变量。这是我在控制台中遇到的错误:
ERROR TypeError: Cannot read property 'nativeElement' of undefined
at onWindowScroll (nav.component.ts:52)
文件
export class NavComponent implements OnInit , AfterViewInit{
@ViewChild("stickyMenu", { static: true }) menuElement: ElementRef;
// test
@ViewChild("myDiv", {static: false}) divView: ElementRef;
showDiv: boolean = false;
constructor(private el: ElementRef,
private scrollDispatcher: ScrollDispatcher) { }
ngOnInit() {
window.addEventListener("scroll", this.onWindowScroll, true);
}
ngAfterViewInit() {
this.scrollDispatcher
.ancestorScrolled(this.el)
.subscribe(event => this.onWindowScroll());
// This logs ABOUT
console.log(this.divView.nativeElement.innerHTML);
}
@HostListener('mouseenter')
onMouseEnter() {
console.log('entered');
this.showDiv = true;
}
@HostListener("window:scroll", ['$event'])
onWindowScroll() {
const windowScroll = window.pageYOffset;
console.log(windowScroll); // is always 0
// this throws an error: Cannot read property 'nativeElement' of undefined
this.divView.nativeElement.innerHTML = "Hello Angular 8!";
}
}
模板
<section class="et-slide" id="about">
<h1 class="header" #myDiv>ABOUT</h1>
<div class="row">
<div
*ngIf="showDiv"
#stickyMenu
[@explainerAnim]
class="col-sm-12 text-center about-page"
(mouseenter)="onMouseEnter()"
>
<div class="card">
<div class="developer-photo mt-4"></div>
<div class="card-body">
<h2>Who`s this guy?</h2>
<p>
ggggggg <br />
gggggggggg.
</p>
</div>
</div>
<div class="card developer-details ">
<div class="card-header developer-header mt-4">
<h2>ggggggggg</h2>
<h5>Full-Stack Developer</h5>
</div>
<div class="card-body">
<p>
ggggggggg.
</p>
<table class="table table-borderless">
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">EMAIL</th>
<td>ggggggggg</td>
</tr>
<tr>
<th scope="row">PHONE</th>
<td>ggggg</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>