6

I have a parent component with the following code in the parent.component.html:

<app-child [idElement]=(idElement)></app-child>

In the child component, I have the input parameter like this:

@Input() idElement : number;

And also a function called

getSpecs()

I want the getSpecs() function to be executed by the child when the input is modified by the parent. Is that possible?

2

3 Answers 3

9

For that purpose, you have to use the Angular lifecycle hook ngOnChanges.

In your case it would be something like:

ngOnChanges(changes: SimpleChanges) {
    if (changes['idElement']) {
        // Do your logic here
        this.getSpecs()
    }
}

The documentation is here.

Sign up to request clarification or add additional context in comments.

Comments

9

There is another option without OnChanges.

@Component({
    selector: 'app-child',
    template: '<div></div>'
})
export class AppChildComponent {
    private _idElement: number;

    get idElement(): number {
        return this._idElement;
    }

    @Input('idElement') set idElement(value: number) {
        if (value) {
            this._idElement = value;
            this.getSpecs();
        }
    }
}

Hope this helps! :)

Comments

1

You can try these one

  1. Import OnChanges from angular core package in your child component

    import { Component, Input, OnChanges , SimpleChanges} from '@angular/core';

  2. Implement you child class like

    export class YourComponent implements OnChanges

  3. Create OnChanges method like

    ngOnChanges(changes:SimpleChanges){
      console.log(changes.your input property name);
     // implement your logic here  
    }
    

Whenever you have changes in parent component it will affect in child component

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.