soumyadeb ghoshal
soumyadeb ghoshal

Reputation: 291

ngOnChanges fails to trigger on change of Input

My angular component is like below:

@Component({
    selector: 'request-Component'
    templateUrls: './request.component.html'
    styleUrls: ['./request.component.scss']
})
export class ChildComponent implements OnInit, OnDestroy, OnChanges {
     @Input() filters: FilterMetadata;
 
     constructor(private service: RequestService){} 

     ngOnInit(): void {this.service.GetRequests(this.filters);}

     ngOnChanges(changes: SimpleChanges): void {
         console.info('ngOnChanges: ', changes['filters']);
         this.service.GetRequests(this.filters);
     }
}

Below is how I am injecting this component in the caller:

<request-Component [filters]='filtersData'></request-Component>

Below is the FilterMetadata interface:

export default interface FilterMetadata{
    country: string;
    state: string;
    city: string;
}

Below is how the input to child is set in the caller component:

setFiltersData() {
    this.FiltersData = {
        country: 'testCountry',
        state: 'testState',
        city: 'testCity'
    }
}

I am able to solve this by explicitly implement a getter and setter on the Input in the child component but I want to know why ngOnChanges is not detecting the change.

Upvotes: 0

Views: 858

Answers (1)

Alireza
Alireza

Reputation: 32

The ngOnChanges method is triggered exclusively when there is a modification in the Input property that originates from a template binding. However, if you manually assign a value to the property like object = {key: newValue}, this occurs outside the change detection cycle, and you must inform Angular explicitly that a change has been made.

Besides getter/setter approach you can use:

updateNewData(newValue) {
  this.object= newValue;
  this.changeDetectorRef.detectChanges();
}

Luckily, ngOnChanges will be invoked.

Upvotes: 0

Related Questions