Search code examples
angulardata-bindingng2-smart-tableangular-input

Unable to send the parameter value to another component using angular ng2-smart-table


I am using Angular ng2-smart-table and am having trouble sending the value of a parameter to another component. The value is coming through as undefined.

Actually, want to enable or disable the toggle button based on the alue received from server

ToogleButtonComponent

  import { Component, OnDestroy, OnInit, EventEmitter, Output, Input } from '@angular/core';

@Component({
  selector: 'ngx-toggle-button',
  template: `<nb-toggle [checked]="isActive" (change)="onToggleChange($event)"></nb-toggle>`,
})
export class ToggleButtonComponent implements OnInit, OnDestroy {
  @Input() isActive: boolean; // This should match the `cell` value
  @Output() toggleButtonChange = new EventEmitter<boolean>();

  constructor() { }

  ngOnInit(): void {
    console.log('Initial isActive:', this.isActive);
  }

  ngOnDestroy(): void {
    this.toggleButtonChange.complete();
  }

  onToggleChange(event: any): void {
    this.isActive = event.target.checked;
    this.toggleButtonChange.emit(this.isActive);
  }
}

ng2-smart-table

settings = {
    hideSubHeader: true,
    actions: {
      columnTitle: 'Manage',
      add: false,  
      edit: false, 
      delete: false
    },
    columns: {
      status: {
        title: 'status',
        type: 'custom',
        renderComponent: ToggleButtonComponent,
        onComponentInitFunction: (instance, row) => {
         
        },
        valuePrepareFunction: (cell) => {
          console.log("cell>>", cell); // Log the cell and getting as true or false
          // Pass the current status (true/false) to the component
          return { isActive: cell };
        }
      },
    },
  };

Solution

  • The input parameter, must be named as value that is the issue. You can access the details inside this value property.

    @Component({
      selector: 'ngx-toggle-button',
      template: `<nb-toggle [checked]="value.isActive" (change)="onToggleChange($event)"></nb-toggle>`,
    })
    export class ToggleButtonComponent implements OnInit, OnDestroy {
      @Input() value: any; // This should match the `cell` value
      @Output() toggleButtonChange = new EventEmitter<boolean>();
    
      constructor() { }
    
      ngOnInit(): void {
        console.log('Initial isActive:', this.value.isActive);
      }
    
      ngOnDestroy(): void {
        this.toggleButtonChange.complete();
      }
    
      onToggleChange(event: any): void {
        this.value.isActive = event.target.checked;
        this.toggleButtonChange.emit(this.value.isActive);
      }
    }
    

    Stackblitz Demo