How to reload a component while in another one?

76 Views Asked by At

I don't know how to use ViewChild feature in my Angular 17 project.

What i'm trying to do is to reload a component when using a function from another component:

Imagine having Component A and Component B and those two are in the same page in two different Mat-Tabs and are called #componentTemplateA and #componentTemplateB.

I have this function in Component A:

activityClicked(event: MatCheckboxChange, activity: ActivityDTO) {
this.activityService
  .changeStatusActivityByCompany(
    this.currentUser.FK_Company,
    activity.ID,
    event.checked
  )
  .subscribe({
    next: (res) => {
      this.getActivitiesByCompany();
    },
    error: (err) => {
      DialogService.Error(err.message);
    },
  });

I'm trying to reload my Component B when clicking on the activityClicked function. That's because in Component A i select some elements through checking the checkbox and what i wish is to instantly have the Component B populated with the elements selected from Component A.

As now it only works if i reload the page after i used the activityChecked function but i want to get instantly updated once i check something.

1

There are 1 best solutions below

0
Eliseo On

@Jany, mat-tab works using "*ngIf" so when one component is visible, the other is not. Tihs is the reason you need "store" the values in some that exists always: a variable in a service or a variable in the component who have the mat-table.

If you pass a complex object to your components using an @Input, you share this object.

A simple example:

//parent
model={id1:0,id2:0,common:0}

<component-A [model]="model"></component-A>
<component-B [model]="model"></component-B>

//component-A
@Input()model:any
<input [(ngModel)]="model.id2">
<input [(ngModel)]="model.common">

//component-B
@Input()model:any
<input [(ngModel)]="model.id1">
<input [(ngModel)]="model.common">

Or you can also use a service with a variable and in ngOnInit of the components equal the variable

//component-A or component-B
<input [(ngModel)]="id">
<input [ngModel]="common" 
       (ngModelChange)="change($event)">

//where
id:number=0
common:number=0
constructor(private serviceData:ServiceData){}

ngOnInit(){
 this.common=this.serviceData.common
}
change($event){
   this.common=$event;
   this.serviceData.common=$event
}