-1

I have a parent component which renders the first child component which is app-deals-transaction , the main component is transactions-details.component and then app-deals-transaction renders 2 child component which is app-deals-approval component and app-table-multi-sort component.

How do I create a service to communicate deals-transaction.component.ts from deals-approval.component.ts ?

What I want is that if there is changes or if _pageEventDealsList is called in deals-transaction.component.ts I also want to call and execute at the same time the _pageEventDealsForApprovalList from deals-approval.component.ts

How do we do that in angular ? that _pageEventDealsForApprovalList from deals-approval.component.ts will execute everytime _pageEventDealsList is called in deals-transaction.component.ts component is called or executed. Thanks.

#app-deals-transaction component html code

<div >
   <app-deals-approval  [transaction]="transaction" ></app-deals-approval> 
  </div>
  <app-table-multi-sort (dataServiceEvent)="dealsServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="data" (tableActionsEvent)="tableActions($event)"></app-table-multi-sort>
</div>

#app-deals-approval component html code <app-table-multi-sort (dataServiceEvent)="dataForApprovalServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="data">

#app-deals-approval component ts code

export class DealsApprovalComponent implements OnInit {
  @ViewChild(TableMultiSortComponent, { static: true }) tableMultiSortComponent: TableMultiSortComponent;
  tableOptions: any;
  @Input() transaction: any;
  @Input() dataTest: any;
  isLoading: boolean;
  private _destroyed$ = new Subject();
  totalDeals : number;
  accountId: any;
  data: any;
  searchInput: string;
  table: any;
  constructor(
    private dialog: MatDialog,
    private dealService: DealService,
    private notificationService: NotificationService,
    private route: Router,
    
  ) {}
  ngOnInit(): void {
    console.log("load here" , this.dataTest)
  
    const currentAccountDetails = localStorage.getItem('currAcct') as any;
    if (currentAccountDetails) {
      this.accountId = JSON.parse(currentAccountDetails).accountId;
    }

    this.tableOptions = {
      columns:[
        {id:'name',name:'Deal Name',subId:'type', subtitle:'Deal Type'},
        {id:'annualRentProposed',name:'Annual Rent (Proposed)', subId: 'annualRentCurrent', subtitle:'Annual Rent (Proposed)'},
        {id:'firmTermRemain',name:'Firm Term Remaining', subId: 'firmTermAdded', subtitle:'(Current)'},
        {id:'maxTerm',name:'Max Available Term'},
        {id:'cash',name:'Cash Contribution'},
      ]
    }
  }

  dataForApprovalServiceEvent(item) {
    this.table = item;
    if(this.table) {
      this._pageEventDealsForApprovalList();
    }
  }

  private _pageEventDealsForApprovalList() {
    this.searchInput = '';
    this.isLoading = true;
    this.dealService
      .getAllForApprovalDeals(
        this.accountId,
        this.transaction.id,
        this.table.pageIndex + 1,
        this.table.pageSize,
        this.searchInput,
        this.table.sortParams,
        this.table.sortDirs
      )
      .pipe(finalize(() => (this.isLoading = false)))
      .subscribe({
        error: (err) => this.notificationService.showError(err),
        next: (res) => {
          this.table.data = res.items;
          console.log("this.table.forApprovalData" , res.items)
        },
        complete: noop,
      });
  }
}

#app-deals-transaction ts code

xport class DealsTransactionComponent implements OnInit {
  @Input() transactionId: any = 2;
  @Input() transactionName: string = '-';
  @ViewChild(TableMultiSortComponent, { static: true }) tableMultiSortComponent: TableMultiSortComponent;
  resetFormSubject: Subject<boolean> = new Subject<boolean>();
  tableOptions: any;
  @Input() transaction: any;
  totalDeals: number;

  isLoading: boolean;
  accountId: any;
  data: any;
  searchInput: string;
  table: any;
  constructor(
    private _snackBar: MatSnackBar,
    private dialog: MatDialog,
    private dealService: DealService,
    private notificationService: NotificationService,
    private route: Router,
    
  ) {}
  ngOnInit(): void {
    const currentAccountDetails = localStorage.getItem('currAcct') as any;
    if (currentAccountDetails) {
      this.accountId = JSON.parse(currentAccountDetails).accountId;
    }

    this.tableOptions = {
      columns:[
        {id:'name',name:'Deal Name',subId:'type', subtitle:'Deal Type'},
        {id:'annualRentProposed',name:'Annual Rent (Proposed)', subId: 'annualRentCurrent', subtitle:'Annual Rent (Proposed)'},
        {id:'firmTermRemain',name:'Firm Term Remaining', subId: 'firmTermAdded', subtitle:'(Current)'},
        {id:'maxTerm',name:'Max Available Term'},
        {id:'cash',name:'Cash Contribution'},
        {id:'action', name: 'Actions', actions:[
          {icon:'file_copy', name:'Copy', class:'primary-color' , },
          {icon:'delete', name: 'Delete', class:'mat-error'},
          {icon:'forward', name: 'For Approval', class:'primary-color' }
        ]}
      ]
    }
  }

  dealsServiceEvent(item) {
    this.table = item;
    if (this.table) {
      this._pageEventDealsList();
    }
  }
  public _pageEventDealsList() {
    this.searchInput = '';
    this.isLoading = true;
    this.dealService
      .getAllDeals(
        this.accountId,
        this.transaction.id,
        this.table.pageIndex + 1,
        this.table.pageSize,
        this.searchInput,
        this.table.sortParams,
        this.table.sortDirs
      )
      .pipe(finalize(() => (this.isLoading = false)))
      .subscribe({
        error: (err) => this.notificationService.showError(err),
        next: (res) => {
          this.table.totalItemCount = res.totalItemCount;
          this.table.lastItemOnPage = res.lastItemOnPage;
          this.totalDeals = res.items.length;
          this.table.data = res.items;
        },
        complete: noop,
      });
  }

#transactions-details.component code

<div class="tab-content">
    <app-deals-transaction *ngIf="tab === 'Deals'" [transaction]="transaction"
        ></app-deals-transaction>
</div>

#app table multi sort component

@Component({
  selector: 'app-table-multi-sort',
  templateUrl: './table-multi-sort.component.html',
  styleUrls: ['./table-multi-sort.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush    
})
export class TableMultiSortComponent implements OnInit, OnChanges {
  @Input() tableOptions:any;
  @Input() tableData:any = [];
  @Input() isClientSide:boolean = false;
  @Input() isLoading: boolean = false;
  @Output() tableActionsEvent = new EventEmitter<any>();
  @Output() dataServiceEvent = new EventEmitter<any>() ;
  @ViewChild(MatMultiSort, { static: false }) sort: MatMultiSort;
  
  tableConfig: any = TABLE_MULTI_SORT_OPTIONS.DEFAULT;
  table:TableData<any>;
  displayedColumns: any;
  
  constructor() { }
  ngOnChanges(changes: SimpleChanges): void {
    console.log("changes" , changes)
  }

  ngOnInit(): void {   
    this.initTableMultiSort();
  }

  initTableMultiSort() {
    this.tableConfig = {
      ...this.tableConfig,
      ...this.tableOptions
    }
    
    this.table = new TableData<any>(this.tableConfig.columns,this.tableConfig.sortParams);
    this.table.pageSize = this.tableConfig.pageSize;
    this.table.pageIndex = this.tableConfig.pageIndex;
    this.table.nextObservable.subscribe(() => { this.getData(); });
    this.table.sortObservable.subscribe(() => { this.getData(); });
    this.table.previousObservable.subscribe(() => { this.getData(); });
    this.table.sizeObservable.subscribe(() => { this.getData(); });

    setTimeout(()=>{
      this.table.dataSource = new MatMultiSortTableDataSource(this.sort, this.isClientSide);
      this.getData();
    },0);
  }
  getData(){
    this.table.totalElements = 1;
    this.table.pageIndex = 0;
    this.table.pageSize = 10;
    this.table.data = this.tableData;

    if(this.dataServiceEvent) {
      this.dataServiceEvent.emit(this.table);
    }
  }

1 Answers1

0

There are two ways -

  • Create a variable in service and share it between components (if you want to share just data)
  • Create rxjs BehaviorSubject in service, subscribe and send event between components as per usecase.

for reference link

rohan
  • 79
  • 3