Home > Software design >  Access child variable value from a parent button action event
Access child variable value from a parent button action event

Time:09-23

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

CodePudding user response:

You should probably take a look at https://angular.io/guide/inputs-outputs#sending-data-to-a-parent-component.

The way to go is to define an EventEmitter in child component:

Output()
dataChanged = new EventEmitter();

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

amd then handling the Event in parent component accordingly (in Typescript define variable):

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

  onClick(): void {
    // now you can use this.childProp here
  }

}
<app-child-panel (dataChange)="childProp = $event">

CodePudding user response:

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

  • Related