微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AppComponent无法使用@ViewChild访问子组件功能,显示错误this.ChildComponent未定义

如何解决AppComponent无法使用@ViewChild访问子组件功能,显示错误this.ChildComponent未定义

我想使用@ViewChild从父组件访问子组件功能,但显示“未定义”错误

我正在尝试实现ngx-infinite-scroll,将滚动应用于父AppComponent,并且当用户向下滚动到底部(滚动)时会触发父AppComponent中的“ onScroll”功能

因此,“ onScroll”切换了子组件中的ngx-spinner的可见性,并且从api提取所有数据并通过子组件开始进行渲染。
请帮助!!!

父组件: AppComponent
儿童组件: .// current / posts / post-card / post-card.component

PARENT-> AppComponent.ts

import { Component,ViewChild} from '@angular/core';
import {PostCardComponent} from './current/posts/post-card/post-card.component';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})

export class AppComponent
{
  @ViewChild(PostCardComponent) child: PostCardComponent ; 
  constructor(){}

  onScroll(){
    console.log("----scrolled-----");
    this.child.showSpinner();
  }
}

儿童-> PostCardComponent

import { Component,OnInit} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import {Title} from "@angular/platform-browser";
import { HttpClient } from '@angular/common/http';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-post-card',templateUrl: './post-card.component.html',styleUrls: ['./post-card.component.css']
})

export class PostCardComponent implements OnInit {
  received = 'none';
  posts: any = [];

  constructor(private http: HttpClient,public spinner: NgxSpinnerService){}

  ngOnInit(){
    this.loadInitPosts();
  }

  public showSpinner(){
    this.spinner.show();
  }

  loadInitPosts(){
    const url = 'http://localhost/api/getPosts.PHP;
    this.http.get(url).subscribe(data => {
      this.posts = data;
      this.received='success';
    },error =>
    {
      this.received='error';
    });
  }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。