As a newcomer to Angular, I've been experimenting with passing data from a parent component to a child component using @Input(), but I'm facing issues with the changes not being reflected. In my parent component, there's a select element and I intend to pass the selected item's value to the children components. The parent component consists of a mat-tab-group containing multiple mat-tabs.
Parent HTML
<mat-form-field>
<mat-select placeholder="Class" [formControl]="selectedClassControl" (selectionChange)="changeClassId()">
<mat-option *ngFor="let class of classes" value="{{class.id}}">{{class.classNumber}}-{{class.section}}</mat-option>
</mat-select>
</mat-form-field>
<mat-tab-group color="primary" (selectedIndexChange)="selectTab($event)">
<mat-tab label="Units">
<app-units [classId]="classId" *ngIf="selectedTab === 0"></app-units>
</mat-tab>
<!-- other tabs with similar structure -->
</mat-tab-group>
Parent TS
classId : number = 0;
classes: Class[];
selectedClass: any;
selectedClassControl = new FormControl(this.selectedClass);
constructor(private classService: ClassService, private stateMgmtService:
StateManagementService) {
var schoolId = this.stateMgmtService.getSchoolId();
this.classService.getClasses(schoolId).subscribe(data =>{
this.classes = data;
})
}
selectedTab = 0;
ngOnInit(): void {
}
selectTab(event) {
this.selectedTab = event;
}
changeClassId(){
this.classId = this.selectedClassControl.value;
console.log("ClassId changed to "+this.classId);
}
Child HTML
<mat-form-field>
<mat-select placeholder="Subject" [formControl]="selectedSubjectControl" >
<mat-option *ngFor="let subject of subjects" value="{{subject.id}}">{{subject.code}}-{{subject.name}}</mat-option>
</mat-select>
</mat-form-field>
Child TS
@Input() classId : number = 0;
subjects: Subject[];
selectedSubject: any;
selectedSubjectControl = new FormControl(this.selectedSubject);
constructor(private classService: ClassService) {
console.log("classId"+this.classId);
if(this.classId != 0)
classService.getSubjects(this.classId).subscribe( data => {
this.subjects = data;
})
}
I've noticed that when I make a selection in the parent component, the classId isn't passed to the child component. Is it necessary for me to manually refresh the component for the changes to take effect?
Any assistance would be greatly appreciated...
Thanks in advance!