Giter Site home page Giter Site logo

Comments (8)

irossimoline avatar irossimoline commented on June 30, 2024

Hi @ulejon,

Yes it is possible. The way I see it you can do it at least in two different ways:
1- If you are defining a ValidatorService instance at the time of creating the datasource, on each new row you instantiate you can access to row.validator.controls['nameOfTheFormControl'], and subscribe to it like in the example you provided. So, in the event that triggers creation of a new row (click on a button for example), instead of calling dataSource.createNew(), you can call a custom method in your component that does the following:

dataSource.createNew(); // Create the new row
const row = dataSource.getRow(-1); // To get the new created row.
... // At this point you can access row.validator, which is a FormGroup with all FormControls inside.

2- Define a (change) event handler in the input asociated with the autocomplete, which calls a method with the current text in the field as a parameter. That method will load the desired data to the list asociated with the autocomplete field as desired.

I hope it helps.

BR

from angular4-material-table.

ulejon avatar ulejon commented on June 30, 2024

Hi and thanx @irossimoline! I will try out approach no 1, I think that is the most fitting solution for me. Much appreciated!

from angular4-material-table.

irossimoline avatar irossimoline commented on June 30, 2024

Great, @ulejon. If you have any issues regarding to that please share your approach with stackblitz or some other. Otherwise, feel free to close the issue.

from angular4-material-table.

ulejon avatar ulejon commented on June 30, 2024

@irossimoline I'm having some issues with approach 1. I'm trying to create a stackblitz that I can show you, but I'm having issues with that as well. I'm unable to add angular4-material-table as a dependency. It says that I also need to install dependency @angular/cdk/collections. Have you successfully created a stackblitz with angular4-material-table?

In the meantime, the main issue with approach 1 is: how do I subscribe to the formcontrols when I load the datasource with the initial values? It's easy when creating a new row, if I follow the instructions you provided in your first comment.
In the example below, how do I subscribe to the form control when the initial objects are fetched in the fetchObjects function?

import {Component, Injectable, OnInit} from '@angular/core';
import {TableDataSource, ValidatorService} from 'angular4-material-table';
import {HttpClient} from '@angular/common/http';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {Observable} from 'rxjs/Observable';


class ModelObject {
  controlId: string
}

@Injectable()
export class ModelObjectValidatorService implements ValidatorService {
  getRowValidator(): FormGroup {
    return new FormGroup({
      'controlId': new FormControl(null, Validators.required)
    });
  }
}

@Injectable()
export class ModelObjectService {

  constructor(private http: HttpClient) {
  }

  getObjects(): Observable<Array<ModelObject>> {
    return this.http.get<Array<ModelObject>>('/my-service/objects');
  }
}

@Component({
  selector: 'app-somecomponent',
  providers: [
    {provide: ValidatorService, useClass: ModelObjectValidatorService}
  ],
  templateUrl: './somecomponent.component.html',
  styleUrls: ['./somecomponent.component.scss']
})
export class SomeComponent implements OnInit {
  displayedColumns = ['column1', 'column2'];

  dataSource: TableDataSource<ModelObject>;

  constructor(private modelObjectService: ModelObjectService,
              private modelObjectValidatorService: ValidatorService) {

    this.dataSource = new TableDataSource<any>([], ModelObject, this.modelObjectValidatorService);
  }

  ngOnInit() {
    this.fetchObjects();
  }

  createNewRow() {
    this.dataSource.createNew();
    const row = this.dataSource.getRow(-1);

    row.validator.controls['controlId']
      .valueChanges
      .distinctUntilChanged()
      .subscribe((data) => {
        console.log(`Row ${row} value: ${data}`);
      });

     // persist new object
  }

  private fetchObjects(): void {
    this.modelObjectService.getObjects()
      .subscribe((modelObjects: Array<ModelObject>) => {
        this.dataSource.updateDatasource(modelObjects);
      });
  }
}

from angular4-material-table.

irossimoline avatar irossimoline commented on June 30, 2024

I didn't use it at stackblitz, but you can start from this example on plunkr.

from angular4-material-table.

ulejon avatar ulejon commented on June 30, 2024

@irossimoline Here's the link to a simple plunkr

If you bring up the console you can see that I it works with subscribing to new rows. But how do I subscribe to the rows initially loaded from the service?

from angular4-material-table.

irossimoline avatar irossimoline commented on June 30, 2024

@ulejon, on that case you can try the following:

  1. Create a new field for your model, that will hold a Subscription value.

  2. On editing rows, check if subscription does not exist before calling row.startEdit(), and create one if not, storing it on the new field of your model. For this, you will have to call the row.startEdit() from a method into your component, like you did with dataSource.createNew().

Your template code will have something like the following:

<button *ngIf="!row.editing" mat-icon-button color="primary" focusable="false" (click)="myStartEdit(row)">
  <i class="fa fa-pencil mat-icon"></i>
</button>

And your component.ts file should have the implementation for the invoked mehod:

myStartEdit(row: TableElement<ModelObject>) {
  // Check if subscription exists.
  if(!row.currentData.subscription) {
    // If does not exists a subscription, create one and store it in the `ModelObject` new field.
  }

  // Now you can start editing.
  row.startEdit();
}
  1. On new rows, create new subscription and store it in the ModelObject new field.

  2. On deleting rows, check if the subscription exists. If exists, then unsubscribe before calling row.delete(). PS: I'm not exactly sure if unsubscribe in this specific case is mandatory to prevent memory leaks or not. Maybe you can try this approach, and investigate a bit further about rxjs subscriptions and memory leaks. If you can't get an answer try raising an issue on Angular or rxjs git repo to ask about this specific case. I'd also encourage you to post your results here for the record.

Tell me about the results of trying this approach.

from angular4-material-table.

ulejon avatar ulejon commented on June 30, 2024

@irossimoline, thank you for the detailed response! I'm pretty sure this approach will solve my problems. I won't be able to try ut out for a couple of days. I'll close this issue for now and later update it with the results.

Thank you again,
Cheers

from angular4-material-table.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.