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.
The
ngOnChangesmethod 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 likeobject = {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:
Luckily,
ngOnChangeswill be invoked.