0

Tengo el siguiente componente HTML

    <ng-container *ngIf="batteryActions$ | async as bateria">
          <app-suggested-actions *ngFor="let batteryAction of bateria"
          [dataActions]="batteryAction"
          [actionsSelected]="actionsSelected"
          (click)="selected(batteryAction)">
          </app-suggested-actions>
    </ng-container>

Es una card, que recibe 2 inputs, dataActions y actionsSelected.

actions selected por defecto es un array vacio:

 actionsSelected:SuggestedActions[] = []

Estas card tienen un metodo llamado selected que se dispara cuando se hace click sobre una card,y recibe la card misma. Este metodo lo que hace es fijarse si esta action esta dentro del array actionsSelected y si no está, lo agrega!

  selected(actionSelected){

    let actionExist = this.actionsSelected.findIndex(action => action.id == actionSelected.id)
    if(actionExist > 0){
      this.actionsSelected.splice(actionExist,1)
      actionSelected.selected = !actionSelected.selected
    } else {
      this.actionsSelected.push(actionSelected)
      console.log(this.actionsSelected);
      actionSelected.selected = !actionSelected.selected

    }
  }

Es en este punto, que necesito saber como detectar que se modifico actionsSelected, para que las otras cards puedan acceder a los nuevos valores.

En el OnInit de todas estas cards, se setea una propiedad order segun los datos de entrada de este input, claro,a lo primero como no hay ninguan seleccionada esta propiedad esta como null, pero cuando se selecciona una necesito que las demas actualicen ese dato de entrada.

HTML CARDS:

<mat-card class="actionCard" [ngClass]="{'actionCard-selected': dataActions.selected}" (click)="changeOrder()">
  <mat-card-content>
        <img [src]="dataActions.url_imagen | errorImage" class="actionCard__img" alt="Photo {{ dataActions.name }}"/>
    <mat-card-title>{{ dataActions.name }}</mat-card-title>
  </mat-card-content>
</mat-card>
{{order}}

TS CARDS:

export class SuggestedActionsComponent implements OnInit {

  @Input()
  dataActions: SuggestedActions;

  @Input()
  actionsSelected: SuggestedActions[];

  order:number;

  constructor() { }

  ngOnInit(): void {
    let actionExist = this.actionsSelected.findIndex(action => action.id == this.dataActions.id)
    this.order = actionExist >= 0 ? actionExist : null
  }


  changeOrder(){
    setTimeout(() => {
    let actionExist = this.actionsSelected.findIndex(action => action.id == this.dataActions.id)
    this.order = actionExist >= 0 ? actionExist + 1 : null
    }, 100);
  }

}

Probe con OnChanges, pero no detecta.

Al hacer click en una card, reviso si en el array actionsSelected ya existe esta card entonces obtengo el indice y se lo asigno a la propiedad order, con el metodo changeOrder() del click, esto me funciona pero para actualizar una card, las demas parecen no enterarse de que cambio actionsSelected.

Le hice click a 3 cards, en orden y se puso correctamente el orden como veran en la imagen, 1, 2 y 3.

introducir la descripción de la imagen aquí

Pero ahora, si toco la 2, deberia la 3 pasar a tener el orden 2 ya que la otra no existe mas en actionsSelected, de hecho actionsSelected paso a tener solo 2 elementos.

export class SuggestedActionsComponent implements OnInit,OnDestroy {

  @Input()
  dataActions: SuggestedActions;

  @Input()
  actionsSelected: SuggestedActions[];

  order:number;

  constructor(private changeService:ChangeOrderActionsSelectedService) { }

  ngOnInit(): void {
    this.changeService.change$.subscribe(() => this.changeOrder())
  }


  changeOrder(){
    let actionExist = this.actionsSelected.findIndex(action => action.id == this.dataActions.id)
    this.order = actionExist >= 0 ? actionExist + 1 : null
  }

  ngOnDestroy(){
    this.changeService.change$.unsubscribe()
  }


}

introducir la descripción de la imagen aquí

1 respuesta 1

1
  1. Crea un servicio con un observabe que servirá para comunicar todos los componentes:

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable()
    export class ChangeService {
    change$ = new BehaviorSubject(null)
    }
    
  2. Inyecta ese servicio y úsalo para notificar a los demás componentes para que actualicen su estado:

    export class SuggestedActionsComponent implements OnInit {
    
    @Input()
    dataActions: SuggestedActions;
    
    @Input()
    actionsSelected: SuggestedActions[];
    
    order:number;
    
    subscription: Subscription // variable para guardar la suscripción
    
    constructor(private changeService : ChangeService) { }
    
    ngOnInit(): void {
    
      this.subscription = this.changeService.change$.subscribe(() => this.changeOrder())
    }
    ngOnDestroy(){
       this.subscription.unsubscribe()
    }
    
    
    changeOrder(){
    
      let actionExist = this.actionsSelected.findIndex(action => action.id == this.dataActions.id)
      this.order = actionExist >= 0 ? actionExist + 1 : null
    
     }
    
    }
    

Puedes notificar el cambio desde el método selected:

selected(actionSelected){

    let actionExist = this.actionsSelected.findIndex(action => action.id == actionSelected.id)
    if(actionExist > 0){
      this.actionsSelected.splice(actionExist,1)
      actionSelected.selected = !actionSelected.selected
    } else {
      this.actionsSelected.push(actionSelected)
      console.log(this.actionsSelected);
      actionSelected.selected = !actionSelected.selected

    }
    // notificar a los demás componentes que deben actualizarse
    this.changeService.change$.next()
  }
12
  • Gracias lobo, para que no quede pegado el observable, en que momento tengo que desuscribirme?
    – Sunset2000
    el 24 ago. 2021 a las 17:37
  • En el this.changeService.change$.next() , me pide un argumento el next, le paso simplemente un true?
    – Sunset2000
    el 24 ago. 2021 a las 17:41
  • Cierra la suscripción en el ngOnDestroy(). Y sí, pásale un true al next().
    – Lobos
    el 24 ago. 2021 a las 17:48
  • Funciona, pero no puedo usar el unsuscribe en el onDestroy de "SuggestedActionsComponent" ,me tira un error. Ahi lo subo en la descripción
    – Sunset2000
    el 24 ago. 2021 a las 18:01
  • Ahi subi el codigo y el error
    – Sunset2000
    el 24 ago. 2021 a las 18:02

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.