Search code examples
angularangular-components

Access child variable value from a parent button action event


Can we possible to access child variable value form a parent button click? child component

@Component({
  selector: 'app-child-panel',
  templateUrl: './child-panel.component.html',
  styleUrls: ['./child-panel.component.scss'],
})
export class childComponent implements OnInit {
  
  selectedItems: any = [];
  constructor() {
  }

  ngOnInit(): void {
    this.data= {};
  }
  updateData(): void{
    this.data ={item:[]}
  }
}

Parent component

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
})
export class ParentComponent {
  childComponent: ChildComponent | undefined;
  constructor() {}

  onClick(): void {
 
  }

}

Is it possible to access child data object inside parent onClick method.

It will be appreciate some one give a solution.

Thanks in advance


Solution

  • You got some options:

    1 - You can use @Input @Output as the other answer suggests.

    2 - You can use a ViewChild property decorator to access the child component as a property in the parent components like this:

    In the parent

    @ViewChild('child', { static: false })
    childComponent: ChildComponent;
     
    onClick(){
      console.log(childComponent.childProp)
      //make sure the prop is public
    }
    

    In the parent template

    <app-child-panel #child></app-child-panel>
    

    3 - you can use a service to comunicate between components, check out this question: https://stackoverflow.com/a/51027980/2025458

    Services might be the way if you think you will have to share date across more than just one parent and one children