Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to call function after the component got the Input data

I have a parent and child component. In the parent I am searching for a user and give the userId via @Input to my child component. This is working.

After my child component is getting the value I want to call a function so that I am getting the card from the user back. How do I do this? I always getting a card is undefined error.

<p (show)="serachForCard()">
  User: {{userId}}
  Card: {{card.id}}
</p>

My Idea was to call a function but it is still not working.

Function in my ts file:

serachForCard() {
        this.cardService.getCardByUserId(this.userId)
            .subscribe(
                (data: Card) => this.card= data
            )
    }
like image 469
lisa Avatar asked Oct 15 '25 13:10

lisa


1 Answers

Implement OnChanges interface inside your child component and call your function from ngOnChanges method.

@Component({
    ...
})
export class MyComponent implements OnChanges {
    @Input() someInput: string;

    ngOnChanges(): void {
        // do something with this.someInput
    }
}

Documentation: OnChanges

A lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes.

like image 120
Patryk Uszyński Avatar answered Oct 18 '25 07:10

Patryk Uszyński



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!