错误类型错误:无法访问属性,this.child未定义

问题描述 投票:0回答:2

我想从我的父组件“ApiaryComponent”调用在子组件“UpdatePinComponent”中声明的函数“initMap”。 这是我的父 ts 文件:

import { AfterViewInit, Component, Input, OnInit } from '@angular/core';
import { ViewChild } from '@angular/core';
import { UpdatePinComponent } from '../leaflet-map/update-pin/update-pin.component';

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


@Input('class')

export class ApiaryComponent implements OnInit, AfterViewInit {

  @ViewChild(UpdatePinComponent) child!:UpdatePinComponent;
// I can't remove the "!", or else it would print : 
// "Property 'child' has no initializer and is not definitely assigned in the constructor."

(...)

getApiaryAttributes(apiaryId)
    {
        this.child.initMap();
    }

  ngAfterViewInit(){
    this.getApiaryAttributes(this.apiaryId);
  }

}

但是当我加载项目时,我收到此控制台错误:

错误 TypeError:无法访问属性“initMap”,this.child 未定义

编辑:这里有一些 html 代码,如果有帮助的话:

    <ul class="actionApiary">
      <li>
        <button class="ApiaryItem" id="addApiaryItem" data-bs-toggle="modal" data-bs-target="#addApiaryModal">+</button>
      </li>
      <li>
        <button class="ApiaryItem" (click)="getApiaryAttributes(apiaryId)" id="updateApiaryItem" data-bs-toggle="modal" data-bs-target="#modifApiaryModal">m</button>
      </li>
      <li>
        <button class="ApiaryItem" id="deleteApiaryItem" data-bs-toggle="modal" data-bs-target="#deleteApiaryModal">-</button>
      </li>
    </ul>
angular typescript
2个回答
0
投票

实际上,使用构造函数似乎是正确的方法。第一次失败是因为我没有在 app.module.ts 中将 UpdatePinComponent 初始化为提供程序。 它仍然不起作用,但它必须来自传单,所以这是一个不同的问题。


0
投票

子组件不能保证在 ngOnInit 生命周期钩子中可用。相反,您应该实现 ngAfterViewInit 挂钩并在那里调用 myFunction。

这是有关它的官方文档:https://angular.io/guide/lifecycle-hooks#responding-to-view-changes

© www.soinside.com 2019 - 2024. All rights reserved.