Iñigo
Iñigo

Reputation: 2016

Trigger function on @Input() changed

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?

Upvotes: 5

Views: 12125

Answers (3)

Dainis Zhogots
Dainis Zhogots

Reputation: 101

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! :)

Upvotes: 9

Bhagwat Tupe
Bhagwat Tupe

Reputation: 1943

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

Upvotes: 1

ahbon
ahbon

Reputation: 512

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.

Upvotes: 9

Related Questions