I have a parent component that is pass the id of a category. But the data in the child component is loaded only once, when the data is passed the first time from parent to child.
If try to pass a different value, the load() function in the child component will not complete the request.
parent.ts:
selectedCategory = '';
onChange(event: any): void {
this.selectedCategory = event.target.value;
}
parent.html:
<select [(ngModel)]="selectedCategory"
(change)="onChange($event)">
<option *ngFor="let category of categories" [value]="category.id" >
{{category.categoryName}}
</option>
</select>
<div *ngIf="selectedCategory">
<app-child [isCategory]="selectedCategory"></app-child>
</div>
child.ts:
dataSource!: any;
@Input() isCategory!: string;
ngOnInit(): void {
this.load();
}
load() {
this.childService.getCategories(this.isCategory).subscribe((data) => {
this.dataSource = data.data
}, error => {})
}
child.html:
<div *ngFor="let data of dataSource">
{{data.title}}
</div>
CodePudding user response:
you can pass your category id to the route
e.g: route module
{ path: 'categories/:id', component: CategoriesComponent }
then get it using snapshot
id: any
constructor(private route: ActivatedRoute)
//using snapshot
this.id= this.route.snapshot.paramMap.get("id");
CodePudding user response:
You can use a set function for the input in the child:
private _isCategory: string;
@Input()
set isCategory(value){
this._isCategory = value;
this.load();
}
load() {
this.childService.getCategories(this._isCategory).subscribe((data) => {
this.dataSource = data.data
}, error => {})
}
Or use the OnChanges component lifecycle
export class ChildComponent implements OnInit, OnChanges {
@Input()
private isCategory: string;
ngOnChanges(changes: SimpleChanges): void {
if (changes.isCategory.currentValue){
this.load();
}
}
}
