Child component calling another child component’s method

Asked

Viewed 1,393 times

1

I have 3 Components, a Component Father, B Son and a C Son

export class A Parent implements OnInit {
  constructor() { 
  }    
}

In Componen B I have a method to create user

export class B Parent implements OnInit {
  constructor() { 
}

create() {
    this.userService.create()
      .subscribe((res) => { 
        // Call other method in Component C
        //this.card.emit(null)  
      }); 
  } 

 }

And now I have a Component C Where I need call the list method

export class C Parent implements OnInit {
    constructor() { 
}

ngOnInit() {
  this.getUsers();
}

getUSers() {
    this.userService.getUsers()
         .subscribe((res) => {  
            this.users = res
          }); 
    } 

}

and Finally my view

    <div class="col s6">
      <list-administrators ></list-administrators>
  </div>

  <div class="col s6" *ngIf="card == 'create'">
    <create-administrator></create-administrator>
  </div>

  <div class="col s6" *ngIf="card == 'details'">
    <details-administrator></details-administrator>
  </div>

  <div class="col s6" *ngIf="card == 'edit'">
    <edit-administrator></edit-administrator>
  </div>

In component B, I have a method to create a user, when he create, I would call the listing of the other child C, how can I do ?

2 answers

0

I can’t tell you if this is the best way to do it. But what you could do is. A - (Father) B - (Son) C - (Son)

-> so HTML must look something like this:

<a>
<b (outputEmit)="emitted()" ></b>
<c #componentC></c>
</a>

In the A controller you can declare an event and receive the creation issue in the B component by executing an action in the C controller.

export class A
@ViewChild('componentC') componentCElement: ElementRef;

emitted() {
    this.componentCElement.MethodQueQuerExecutar();
}

0

Thanks Renan Degrandi, I ended up using a service, sharing the data with other components is much more efficient, because I would not need to create repeated codes, so sharing ....: Service export class Eventsservice {

  teste = new EventEmitter<boolean>();

 constructor() { }

 getEvent(event: any) {
   this.teste.emit(event);
 }

}

With this I can exchange data with other Components at runtime, now Component B Component B create() { this.userService.create() . subscribe(res) => { ... this.eventService.getEvent(true); }); }

this way sending there any value or desirable object and now, in my case, I can check this value and if it is true in the Komponent C, I call the ngOnInit of the Komponent C to make again the listing of the data I wanted, in this way ... Component C ngOnInit() { this.eventService.card.subscribe((res) => { if(res) this.getUsers(); }) this.getUsers(); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.