This is parent.html
<child *ngFor="let detail of listContact; let i = index"
[detailsItem]="detail" [index]="i">
</child>
This is child.compenent
export class ChildComponent implements OnInit {
@Input() index: number;
@Input() detailsItem: any;
constructor() {
}
ngOnInit() {
}
saveChild(){
console.log('index', this.index);
}
}
And I want to call the method saveChild in parentComponent like this:
export class ParentComponent implements OnInit {
private child: ChildComponent;
@Input() index: number;
@Input() detailsItem: any;
constructor() {
}
ngOnInit() {
}
save(){
this.child.saveChild();
}
}
you can use @ViewChild to run that.
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { ChildComponent } from '../child/child.component';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) public child!:ChildComponent
constructor() { }
ngAfterViewInit(): void {
this.child.childMethod();
}
}
It's going to let you access the properties and methods inside the ChildComponent. However remember to use ngAfterViewInit so that the child is initialised when you try and access it.