How can we transfer a value from a parent component class to a child subclass?

In my TypeScript file, there are three classes within a single file. I am attempting to transfer a value from the MainComponent class to the TableContent class.

I initially tried using super() inside the TableContent class which did not work, and then attempted @Injectable, but encountered an error.

If anyone could provide guidance on how to pass this value from the MainComponent class to the TableContent Class so that I can access it in the constructor of the MainComponent class, it would be greatly appreciated.

main.component.ts

@Component({
  templateUrl: './main.component.html'
})
export class MainComponent implements OnInit {
    public PassThisChild:any;
    public dataTable: any[];
    public sortedData;

    public displayedColumns = ['userId', 'userName', 'progress', 'color'];
    public tableContent = new TableContent();
    public dataSource: TableControlClass | null;
    @ViewChild(MatSort) public sort: MatSort;
    @ViewChild('filter') public filter: ElementRef;

    constructor(private _apiService: ApiService) {
      this._apiService.getTableData()
      .subscribe(
                data => {
                  this.PassThisChild = data;  // i want to pass this
                },
                error => {
                  console.log(error);
                }
              );
    }

    public ngOnInit() {
      this.dataSource = new TableControlClass(this.tableContent, this.sort);
      Observable.fromEvent(this.filter.nativeElement, 'keyup')
      .debounceTime(150)
      .distinctUntilChanged()
      .subscribe(() => {
        if (!this.dataSource) { return; }
        this.dataSource.filter = this.filter.nativeElement.value;
      });
    }
}

    const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
    'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
    const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
    'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
    'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

    export interface UserData {
          id: string;
          name: string;
          progress: string;
          color: string;
    }

export class TableContent {
  public storeHere:any;   // Here i want to access 
  public dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
    get data(): UserData[] { return this.dataChange.value; }
      constructor() {
        for (let i = 0; i < 6; i++) { this.addUser(); }
    }
    private addUser() {
      const copiedData = this.data.slice();
      copiedData.push(this.createNewUser());
      this.dataChange.next(copiedData);
    }
    private createNewUser() {
      const name =
          NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
          NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';
      return {
        id: (this.data.length + 1).toString(),
        name: name,
        progress: Math.round(Math.random() * 100).toString(),
        color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
      };
    }
}

export class TableControlClass extends DataSource<any> {
  public _filterChange = new BehaviorSubject('');
  get filter(): string { return this._filterChange.value; }
  set filter(filter: string) { this._filterChange.next(filter); }

  private filteredData: UserData[] = [];

  constructor(private _tableContent: TableContent, private _sort: MatSort) {
    super();
  }
  public connect(): Observable<UserData[]> {
  const displayDataChanges = [this._tableContent.dataChange, this._filterChange, this._sort.sortChange];

  return Observable.merge(...displayDataChanges).map(() => {
    // Filter data
    this.filteredData = this._tableContent.data.slice().filter((item: UserData) => {
      let searchStr = (item.name + item.color).toLowerCase();
      return searchStr.indexOf(this.filter.toLowerCase()) !== -1;
    });

    return this.sortData(this.filteredData.slice());
  });
}

  public disconnect() { }

  public sortData(data: UserData[]): UserData[] {
    if (!this._sort.active || this._sort.direction === '') { return data; }
    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';
      switch (this._sort.active) {
        case 'userId': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'userName': [propertyA, propertyB] = [a.name, b.name]; break;
        case 'progress': [propertyA, propertyB] = [a.progress, b.progress]; break;
        case 'color': [propertyA, propertyB] = [a.color, b.color]; break;
      }
      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;
      return (valueA < valueB ? -1 : 1) * (this._sort.direction === 'asc' ? 1 : -1);
    });
  }
}

If someone could advise on how to successfully transfer this value between the MainComponent and TableContent classes, specifically accessing it within the MainComponent constructor, it would be very helpful.

Answer №1

To successfully send this.PassThisChild to the TableContent class during initialization, you can relocate the creation code for TableControllerClass inside the _apiService subscription block in the following manner:

// MainComponent Class

this._apiService.getTableData().subscribe(data => {
    this.PassThisChild = data;
    this.tableContent = new TableContent(this.PassThisChild);
    this.dataSource = new TableControlClass(this.tableContent, this.sort);
  },
  error => {
    console.log(error);
  });

// TableContent Class 

export class TableContent {
  constructor(public storeHere){}
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Partial Types in TypeScript Getter and Setter Functions

Within the Angular framework, I have implemented a component input that allows for setting options, specifically of type IOptions. The setter function does not require complete options as it will be merged with default options. Therefore, it is typed as Pa ...

Utilizing SVG Images on Buttons within Material Design (MD-Icon)

I have experimented with different methods, but none seem to be effective: <button md-icon-button color="primary"> <md-icon md-svg-src="./assets/img/sprites.svg">menu</md-icon> </button> and also tried this: <md-icon svgSrc= ...

The method `this.http.post(...).map` is not recognized as a valid function

doSelectMessagesAttributesUrl1(pushRequest : PushRequest) { console.info("sending post request"); let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'}); return this.http .post(th ...

Tabs justified are not constrained by width

Utilizing Bootstrap 3, I aim to have the Tabs align perfectly with the full content. The use of nav-tabs can be observed in the code below. It may seem a bit unusual due to my implementation of Angular 4 and the code being copied from Dev Tools. <ul cl ...

Using TypeScript to automatically deduce the output type of a function by analyzing the recursive input type

I am currently working on developing an ORM for a graph database using TypeScript. Specifically, I am focusing on enhancing the "find" method to retrieve a list of a specific entity. The goal is to allow the function to accept a structure detailing the joi ...

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

The initial processing step for the export namespace is to utilize the `@babel/plugin-proposal-export-namespace-from` plugin. Previous attempts to resolve this issue have been

I encountered a problem with my application and found two related questions on the same topic. However, due to a lack of reputation, I am unable to comment or ask questions there. That's why I'm reaching out here... Recently, I integrated Redux ...

Accessing collection values from referenced document IDs in Firestore---I have provided a unique version of the text

I have two fire store collections with the following reference images: . I am trying to retrieve the firstName and title from these collections. The signup_id is referenced from the document id of coll-signup. Below is the code snippet of what I have done ...

How can I solve export issues from index.ts after publishing to NPM?

I have a package called this package which contains an index.ts file. The corresponding index.d.ts file that is located in the directory node_modules/@fireflysemantics/slice has the following content: export { EStore } from './EStore'; export { ...

Strategies for splitting a component's general properties and accurately typing the outcomes

I am attempting to break down a custom type into its individual components: type CustomType<T extends React.ElementType> = React.ComponentPropsWithoutRef<T> & { aBunchOfProps: string; } The code appears as follows: const partitionProps = ...

Angular 5 error handler does not support service calls

My HTTP calls are placed inside a service, as they should be. Within that service, I inject another service for handling error notifications. In an interesting turn of events, I noticed that when I place the notification call inside the catchError pipe, e ...

How to retrieve the parent activated route in Angular 2

My route structure includes parent and child routes as shown below: { path: 'dashboard', children: [{ path: '', canActivate: [CanActivateAuthGuard], component: DashboardComponent }, { path: & ...

Utilize the composite primary key of an Entity within Typeorm for efficient data retrieval

I am working with the following database entities: @Entity() class Team { @PrimaryGeneratedColumn() id: string @PrimaryColumn() teamName: string @OneToMany(() => Player, player => player.team) players: Player[] } @Entity() class Player ...

Ways to conceal a table and button in the absence of data for display

I've been working on a way to hide the table and the 'changeState' button when there's no data present. Currently, I have set it up so that a message saying 'No entries in the list!' pops up briefly before disappearing, bringi ...

Error: The property ɵfac cannot be redefined within angular

core.js:27478 Uncaught TypeError: Cannot redefine property: ɵfac at Function.defineProperty (<anonymous>) at addDirectiveFactoryDef (core.js:27478:1) at compileComponent (core.js:27361:1) at ɵ3$1 (core.js:27674:93) at TypeDecora ...

What could be the reason behind the malfunction of nativescript-phone on Android during plugin build?

I am encountering a particular build error while trying to deploy our NativeScript app on my Android Studio Emulator: > Failed to build plugin nativescript-phone : Error: spawn ./gradlew ENOENT Exception in thread "DisconnectableInputStream source ...

The variable 'xxx' is not defined in this context

I am attempting to incorporate a dark theme into ngx-charts, and I'm relatively new to using less. Here is the code snippet: My IDE is showing an error message "Cannot find variable 'color-bg-darker'" which leads to compilation failure. Err ...

Ways to display an icon in Angular 10 only when it is hovered over

Just getting started with Angular and still learning the concepts. Trying to figure out how to show an icon only when it's hovered over. Can anyone assist me? Sorry, can't share the code because of company rules. The icons are for sorting and ...

Encountered a PrismaClientValidationError in NextJS 13 when making a request

I am currently working on a school project using NextJS 13 and attempting to establish a connection to a MYSQL database using Prisma with PlanetScale. However, when trying to register a user, I encounter the following error: Request error PrismaClientValid ...

Update ng-Bootstrap ToDate field by removing the date when selecting a fromDate

Is there a way to clear the date from the toDate input field while selecting a date from the fromDate input field in ng-bootstrap? <form class="row row-cols-sm-auto" *ngIf="showDateRangeImp"> <div class="col-12" ...