Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Pass data from parent component to child component on button clicked at parent component

At parentComponenet.html

</div><button(click)="discoverClicked()">Discover</button></div>
<child-component></child-component>

At parentComponent.ts

export class parentComponent implements OnInit {
    discoverClicked(){
       //send data to childComponent
    }
}

At childComponent.ts

export class childComponent implements OnInit {
    discoverClicked(){
       //received data from parent component
    }
}

Is there a way to do as per described above?

like image 504
Sasa Avatar asked Dec 17 '25 12:12

Sasa


1 Answers

Depends on your data, one way of doing so is to introduce some variable, for example in parent component:

@Component(...)
export class ParentComponent {
    private data: any;

    discoverClicked(){
        // do the thing
        this.data = "some data not matter how you got it";
    }
}

And in parent-component.html:

</div><button(click)="discoverClicked()">Discover</button></div>
<child-component [data]=data></child-component>

Then in child component:

@Component(...)
export class ChildComponent {

    @Input('data')
    set data(data: any) {
        //do whatever you want with your data here, this data will be passed from parent component
    }
}

If you need more complex behavior you can make some service which will hold data for you and then pass it to child component, for example:

@Injectable()
export class DataService {
    private _data: BehaviorSubject<any> = new BehaviorSubject<any>(null);

    public setData(data: any){
        this._data.next(data);
    }

    public getData(): Observable<any> {
        return this._data.asObservable();
    }
}

Then in parent component:

@Component(...)
export class ParentComponent {

    constructor(private dataService: DataService){}

    discoverClicked(){
        // do the thing
        this.dataService.setData("any data that you want");
    }
}

And in child component:

@Component(...)
export class ChilComponent{

    constructor(private dataService: DataService){
        this.dataService.getData().subscribe(data=>{
            // Do whatever you want with your data
        }
    }

}

P.S. Don't forget to provide service somewhere and unsubscribe from data in child component.

like image 132
Dmytro Grynets Avatar answered Dec 19 '25 06:12

Dmytro Grynets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!