I'd like to call the function "initMap", declared in the child "UpdatePinComponent", from my parent component "ApiaryComponent". Here is my parent ts file :
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);
}
}
But when I load the project, I am getting this console error :
ERROR TypeError: can't access property "initMap", this.child is undefined
EDIT : here is a bit of the html code, if it can help :
<ul >
<li>
<button id="addApiaryItem" data-bs-toggle="modal" data-bs-target="#addApiaryModal"> </button>
</li>
<li>
<button (click)="getApiaryAttributes(apiaryId)" id="updateApiaryItem" data-bs-toggle="modal" data-bs-target="#modifApiaryModal">m</button>
</li>
<li>
<button id="deleteApiaryItem" data-bs-toggle="modal" data-bs-target="#deleteApiaryModal">-</button>
</li>
</ul>
CodePudding user response:
A child component is not assured to be available is the ngOnInit lifecycle hook. Instead you should implement the ngAfterViewInit hook and call myFunction there.
Here is the official documentation about it: https://angular.io/guide/lifecycle-hooks#responding-to-view-changes
CodePudding user response:
Actually, using a constructor seems to be the proper way. It failed at the first time because I didn't initialized UpdatePinComponent as a provider in the app.module.ts. It still doesn't work, but it must come from leaflet, so this is a different problem.