IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Angular Discussion :

Afficher une datatable après une selection d'un mat-option


Sujet :

Angular

  1. #1
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut Afficher une datatable après une selection d'un mat-option
    Bonjour à tous,

    Je n'arrive pas à mettre en place une datatable qui s'affiche après sélection d'un bouton par un utilisateur.
    Le but est que l'utilisateur sélectionner un bouton, une fois la selection faite, un nouveau get part pour récupérer un JSON et afficher le contenu dans un tableau.

    Actuellement ce qui fonctionne :
    L'utilisateur peut selectionner, le get est envoyé, le contenu est OK je peut le récupérer et l'afficher mais la table ne se remplit pas car je ne vois pas comment initialiser la table ou la remplir une fois le get récupéré.
    La datatable au niveau html est correcte. C'est vraiment au niveau de comment l'initialiser qu'il y a un problème.
    J'utilise "async" et ne veut pas utiliser "subscribe".

    Code HTML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    <!-- WORKING -->
    <form class="example-form">
      <mat-form-field class="example-full-width">
        <input type="text" placeholder="Namespace" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" > 
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)='getServices($event.option.value)'>
    <mat-progress-bar mode="buffer"></mat-progress-bar>
          <mat-option *ngFor="let option of filteredOptions | async" [value]="option.namespace">
            {{option.namespace}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </form>
     
     
     <!-- WORKING -->
    <form class="example-form" *ngIf="services">
      <mat-form-field class="example-full-width">
        <input type="text" placeholder="Namespace" aria-label="Number" matInput [formControl]="myControl2" [matAutocomplete]="auto2" > 
        <mat-autocomplete #auto2="matAutocomplete">
    <mat-progress-bar mode="buffer"></mat-progress-bar>
          <mat-option *ngFor="let service of services | async" [value]="service.service">
            {{service.service}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </form>
     
     
     
     
     <!-- EMPTY -->
    <div class="wrapper" *ngIf="services">
      <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8" >
     
        <ng-container matColumnDef="id" *ngFor="let service of services | async">
          <th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
          <td mat-cell *matCellDef="let service"> {{service.id}} </td>
        </ng-container>
     
        <ng-container matColumnDef="service" *ngFor="let service of services | async">
          <th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
          <td mat-cell *matCellDef="let service"> {{service.service}} </td>
        </ng-container>
     
     
     
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>
     
      <!-- Angular 8 pagination -->
      <mat-paginator [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>
    </div>


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    import { Component, OnInit, Injectable, ViewChild } from '@angular/core';
    import { RestApiService } from '../shared/rest-api.service';
    import { FormControl } from '@angular/forms';
    import { Observable, of, Subscription } from 'rxjs';
    import { tap, startWith, debounceTime, switchMap, map, filter, distinctUntilChanged } from 'rxjs/operators';
    import {MatPaginator} from '@angular/material/paginator';
    import {MatSort} from '@angular/material/sort';
    import {MatTableDataSource} from '@angular/material/table';
     
    @Injectable({
      providedIn: 'root'
    })
     
    @Component({
      selector: 'app-services-namespace',
      templateUrl: './services-namespace.component.html',
      styleUrls: ['./services-namespace.component.scss']
    })
     
    export class ServicesNamespaceComponent implements OnInit {
     
      myControl = new FormControl();
      myControl2 = new FormControl();
      options = [];
      filteredOptions: Observable<any[]>;
      namespaces = [];
      services: Observable<any[]>;
     
      displayedColumns: string[] = ['id', 'service'];
      dataSource: MatTableDataSource<any>;
     
      @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
      @ViewChild(MatSort, { static: true }) sort: MatSort;
     
     
     
      constructor(private dataService: RestApiService) {
         this.filteredOptions = this.myControl.valueChanges.pipe(
          startWith(''),
          debounceTime(500),
          distinctUntilChanged(),
          switchMap(val => {
                return this.filter(val || '')
           }) 
        )
       }
     
       ngOnInit() { 
     
      }
     
     
      filter(val: string): Observable<any[]> {
        // call the service which makes the http-request
        return this.dataService.getAllNameSpaces()
         .pipe(
           map(response => response.filter(option => { 
             return option.namespace.toLowerCase().indexOf(val.toLowerCase()) === 0
           }))
         )
     
       }  
     
     
       getServices(namespace){   
        this.services = this.dataService.getAllServices("services");  
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      }
     
     
     
    }


    Service Rest pour les call de GET
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { tap, startWith, debounceTime, switchMap, map } from 'rxjs/operators';
    import { Observable, of, Subscription } from 'rxjs';
     
    @Injectable({
      providedIn: 'root'
    })
    export class RestApiService {
     
      private REST_API_SERVER_BASE_LINK = "http://localhost:3000";
     
      constructor(private httpClient: HttpClient) { }
     
      data = [];
     
      public getAllNameSpaces(){
        return this.httpClient.get<any>(this.REST_API_SERVER_BASE_LINK + '/namespace').pipe(tap(data => this.data = data));
      }
     
    // Le GET concerné est ici 
      public getAllServices(namespace) : Observable<any[]> {
        return this.httpClient.get<any[]>(this.REST_API_SERVER_BASE_LINK + '/' + namespace).pipe(tap(data => this.data = data));
      }
    }
    Merci pour l'aide
    En image ce que ça donne actuellement
    Nom : téléchargement.png
Affichages : 2065
Taille : 27,1 Ko

  2. #2
    Membre extrêmement actif
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Par défaut
    petit test, rajoute ça à la fin du HTML
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
         <ng-container *ngFor="let service of services | async">
            {{service|json}}
            <hr>
          </ng-container>



    namespace ---> n'est jamais utilisé dans ton code ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
       getServices(namespace){   
        this.services = this.dataService.getAllServices("services");  
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    
       //
        // petit test
        this.dataService.getAllServices("services").subscribe((res: any) => {
            console.log(res);
        }); 
    }
    que donne le console.log(res) ?

  3. #3
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    Ta boucle ng for retourne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    { "id": "0", "service": "fo", "tag": "latest" }
    { "id": "1", "service": "mo", "tag": "19" }
    Le namespace n'est pas utilisé actuellement pour les tests, mais tout est prévu pour l'activer en un petit changement ( rien d'anormal )

    Ton petit test :
    Strictement rien, rien du tout.

    Info : Le problème viens simplement de comment j'ai placé mes this.datasource.. en fait étant nouveau sur angular depuis 3 jours lol je ne vois pas du tout comment les mètres, je les ai mis là car ça me semblait logique mais je pense qu'ils n'ont rien à faire là..

    PS : Merci de laisser le contenu du message svp lors d'edit.. il manque la moitiée.. je la remet

  4. #4
    Membre très actif
    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2019
    Messages
    707
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2019
    Messages : 707

  5. #5
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    @krakatoa Aucune phrase ?
    Le filtrage des données est côté client donc oui ce code est correct.
    Regarde le lien que tu m'as envoyé.. ils en parlent..

  6. #6
    Membre extrêmement actif
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Par défaut
    si je prend un exemple du tuto
    je constate que tu ne respecte pas le code

    dans ton code tu met: <th <td alors qu'il ne doit pas en avoir

    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <mat-table class="lessons-table mat-elevation-z8" [dataSource]="dataSource">
     
        <ng-container matColumnDef="seqNo">
            <mat-header-cell *matHeaderCellDef>#</mat-header-cell>
            <mat-cell *matCellDef="let lesson">{{lesson.seqNo}}</mat-cell>
        </ng-container>
     
        <ng-container matColumnDef="description">
            <mat-header-cell *matHeaderCellDef>Description</mat-header-cell>
            <mat-cell class="description-cell"
                      *matCellDef="let lesson">{{lesson.description}}</mat-cell>
     
        </ng-container>
     
        <ng-container matColumnDef="duration">
            <mat-header-cell *matHeaderCellDef>Duration</mat-header-cell>
            <mat-cell class="duration-cell"
                      *matCellDef="let lesson">{{lesson.duration}}</mat-cell>
        </ng-container>
     
        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
     
        <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
     
    </mat-table>



    ***
    ensuite: MatTableDataSource
    c'est quoi le code ?
    tu l'as bien écrit ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    dataSource: MatTableDataSource<any>;

  7. #7
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    Voila un exemple de stackblitz que j'ai adapté, il est fonctionnel. https://stackblitz.com/edit/angular-8rzmja
    La différence entre ce stackblitz et mon code c'est que de mon coté je ne veux pas que ce soit fait au chargement premier de la page mais après une selection de l'utilisateur.

    Pour ce qui est du respect du code, je te renvoi vers la doc Angular Material -> https://material.angular.io/components/table/overview

  8. #8
    Membre très actif
    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2019
    Messages
    707
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2019
    Messages : 707
    Par défaut
    toujours difficile d'aider quand on a pas étudier les datatables material

    voici ce que j'ai testé sur ton stackblitz

    table-pagination-example.ts
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    import {Component, OnInit, ViewChild} from '@angular/core';
    import {MatPaginator} from '@angular/material/paginator';
    import {MatSort} from '@angular/material/sort';
    import {MatTableDataSource} from '@angular/material/table';
     
    /**
     * @title Table with pagination
     */
    @Component({
      selector: 'table-pagination-example',
      styleUrls: ['table-pagination-example.css'],
      templateUrl: 'table-pagination-example.html',
    })
    export class TablePaginationExample implements OnInit {
      displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
      dataSource = new MatTableDataSource<any>(ELEMENT_DATA);
     
      @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
     @ViewChild(MatSort, { static: true }) sort: MatSort;
     
      ngOnInit() {
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      }
     
      click1() {
        this.dataSource = new MatTableDataSource<any>(ELEMENT_DATA2);
      } 
     
    }
     
     
     
    const ELEMENT_DATA: any[] = [
      {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
      {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
      {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
      {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
      {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
      {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
      {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
      {position: 11, name: 'Sodium', weight: 22.9897, symbol: 'Na'},
      {position: 12, name: 'Magnesium', weight: 24.305, symbol: 'Mg'},
      {position: 13, name: 'Aluminum', weight: 26.9815, symbol: 'Al'},
      {position: 14, name: 'Silicon', weight: 28.0855, symbol: 'Si'},
      {position: 15, name: 'Phosphorus', weight: 30.9738, symbol: 'P'},
      {position: 16, name: 'Sulfur', weight: 32.065, symbol: 'S'},
      {position: 17, name: 'Chlorine', weight: 35.453, symbol: 'Cl'},
      {position: 18, name: 'Argon', weight: 39.948, symbol: 'Ar'},
      {position: 19, name: 'Potassium', weight: 39.0983, symbol: 'K'},
      {position: 20, name: 'Calcium', weight: 40.078, symbol: 'Ca'},
    ];
     
    const ELEMENT_DATA2: any[] = [
      {position: 1, name: 'Hydrogen2', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium2', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium2', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium2', weight: 9.0122, symbol: 'Be'},
      {position: 5, name: 'Boron2', weight: 10.811, symbol: 'B'},
    ];


    table-pagination-example.html
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     <button (click)="click1()">click1</button>
    ...
    ...

  9. #9
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    Merci pour ton test, mais tu vois bien que toi aussi tu initialise tout dès le début avec des données dedans, et que tu fais un update après. J'ai déja vu ce test quelque part.
    Mais ça ne correspond pas à mon besoin de load de la data après un get à la manière que je le fais.

    Pour info ton stack "parait fonctionner" mais en réalité non, tu vois que la génération des pages une fois le click fait n'est pas réalisée

    Après le problème n'est qu'un problème d'Angular simplement basique, je sais générer au chargement de la page mais je ne sais pas générer après le chargement..
    La solution doit tenir en 3 lignes.. mais étant nouveaux..

  10. #10
    Membre très actif
    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2019
    Messages
    707
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2019
    Messages : 707
    Par défaut
    je dois avouer que je ne comprends pas ta demande, désolé !

    ngOnInit() est appelé à la fin du chargement d'une page, il se fait qu'une seule fois donc
    cela fait partie du cycle de vie d'Angular (voir doc)
    je ne sais pas si ça reponds à ta question
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
       ngOnInit() { 
             this. getServices(..........
      }

  11. #11
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    Je vais tenter de re expliquer ma demande.
    Je pense que tu n'as pas vu la photo, je la remet
    Nom : téléchargement.png
Affichages : 1995
Taille : 27,1 Ko


    Le but :
    1) L'utilisateur arrive sur une page avec un champs d'autocomplétion.
    2 ) L'utilisateur tape le "namespace" qu'il recherche, les valeurs s'affichent et son filtrées en fonction de la recherche.
    3 ) Une fois le namespace trouvé, l'utilisateur clique dessus, par exemple "monnamespace".
    4) De la "monnamespace" est envoyé dans la methode getAllServices(namespace...). Cette méthode retourne un Json de résultat qui doit être affiché dans un tableau !
    5 ) Le tableau est affiché en fonction de l'étape 3, la tableau se detruit et se refait si l'utilisateur change sa sélection.

    Donc : Au début, à la fin du chargement de la page, aucun tableau doit être affiché, simplement le champs d'autocompétion. Et c'est après la sélection faite que le tableau apparait !

    J'espère que la c'est parfaitement clair

  12. #12
    Membre très actif
    Homme Profil pro
    Développeur Web
    Inscrit en
    Janvier 2019
    Messages
    707
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2019
    Messages : 707
    Par défaut
    **** 1
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    import {Component, OnInit, ViewChild} from '@angular/core';
    import {MatPaginator} from '@angular/material/paginator';
    import {MatSort} from '@angular/material/sort';
    import {MatTableDataSource} from '@angular/material/table';
     
    /**
     * @title Table with pagination
     */
    @Component({
      selector: 'table-pagination-example',
      styleUrls: ['table-pagination-example.css'],
      templateUrl: 'table-pagination-example.html',
    })
    export class TablePaginationExample implements OnInit {
      displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
      dataSource = new MatTableDataSource<any>;
     
      @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
     @ViewChild(MatSort, { static: true }) sort: MatSort;
     
      ngOnInit() {
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      }
     
      click1() {
        this.dataSource = new MatTableDataSource<any>(ELEMENT_DATA1);
      } 
     
      click2() {
        this.dataSource = new MatTableDataSource<any>(ELEMENT_DATA2);
      } 
    }
     
     
     
    const ELEMENT_DATA1: any[] = [
      {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
      {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
      {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
      {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
      {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
      {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
      {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
      {position: 11, name: 'Sodium', weight: 22.9897, symbol: 'Na'},
      {position: 12, name: 'Magnesium', weight: 24.305, symbol: 'Mg'},
      {position: 13, name: 'Aluminum', weight: 26.9815, symbol: 'Al'},
      {position: 14, name: 'Silicon', weight: 28.0855, symbol: 'Si'},
      {position: 15, name: 'Phosphorus', weight: 30.9738, symbol: 'P'},
      {position: 16, name: 'Sulfur', weight: 32.065, symbol: 'S'},
      {position: 17, name: 'Chlorine', weight: 35.453, symbol: 'Cl'},
      {position: 18, name: 'Argon', weight: 39.948, symbol: 'Ar'},
      {position: 19, name: 'Potassium', weight: 39.0983, symbol: 'K'},
      {position: 20, name: 'Calcium', weight: 40.078, symbol: 'Ca'},
    ];
     
    const ELEMENT_DATA2: any[] = [
      {position: 1, name: 'Hydrogen2', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium2', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium2', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium2', weight: 9.0122, symbol: 'Be'},
      {position: 5, name: 'Boron2', weight: 10.811, symbol: 'B'},
    ];

    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    <button (click)="click1()">click1</button>
    <button (click)="click2()">click2</button>
    ...
    ...


    click1 et click2 fonctionne très bien, le tableau se met à jour





    **** 2
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    ...
    <form class="example-form" *ngIf="services">
      <mat-form-field class="example-full-width">
        <input type="text" placeholder="Namespace" aria-label="Number" matInput [formControl]="myControl2" [matAutocomplete]="auto2" > 
        <mat-autocomplete #auto2="matAutocomplete">
    <mat-progress-bar mode="buffer"></mat-progress-bar>
          <mat-option *ngFor="let service of services | async" [value]="service.service"   (click)="selection(service.id)">
            {{service.service}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </form>


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    selection(id) {
        const item =   .... recherche le service dont ID = id
        this.dataSource = new MatTableDataSource<any>(item);
    }

  13. #13
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    ***1 : Le tableau se met à jour au niveau data oui, mais pas au niveau du tableau en lui même. Il affiche au click 2 , un 0 of 0 et pages se génère pas si tu force la page à contenir une data par page.
    (mais aucun interet de toute manière ça ne répond pas au besoin)

    ***2 : La désolé mais c'est totalement incohérent avec les points mentionnés.. Ton code HTML ne répond pas du tout à l'image que j'ai donné.

    J'ai indiqué : Un champs ou tu renseigne le namespace, tu clique sur le namespace et un tableau de service se génère.

    Dans ton cas il n'y a même plus de sélection du namespace tu l'a supprimé.. et t'es partit dans une sélection du service alors que j'ai jamais parlé de sélectionner un service...
    La photo indique bien que le bouton de sélection des services était juste la pour vérifier que ma data était lisible.
    Tu es entrain de toucher au code que j'ai dis comme un test d'affichage..

    Le texte que j'ai décris d'un point de vue utilisateur est super clair, compare mon texte avec le code que tu me proposes, c'est juste totalement incohérent


    Le code HTML est bon, ce qui ne l'est pas c'est coté Angular.
    Je t'invite à relire lentement le besoin utilisateur pour voir que le code html tel qui est écrit est bon.

    Pour t'aider à comprendre voila le code html sans le test d'affichage :

    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    <form class="example-form">
      <mat-form-field class="example-full-width">
        <input type="text" placeholder="Namespace" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" > 
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)='getServices($event.option.value)'>
    <mat-progress-bar mode="buffer"></mat-progress-bar>
          <mat-option *ngFor="let option of filteredOptions | async" [value]="option.namespace">
            {{option.namespace}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </form>
     
     
    <div class="wrapper" *ngIf="services">
      <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8" >
     
        <ng-container matColumnDef="id" *ngFor="let service of services | async">
          <th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
          <td mat-cell *matCellDef="let service"> {{service.id}} </td>
        </ng-container>
     
        <ng-container matColumnDef="service" *ngFor="let service of services | async">
          <th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
          <td mat-cell *matCellDef="let service"> {{service.service}} </td>
        </ng-container>
     
     
     
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </table>
     
      <!-- Angular 8 pagination -->
      <mat-paginator [pageSizeOptions]="[5, 10, 15]" showFirstLastButtons></mat-paginator>
    </div>

  14. #14
    Membre extrêmement actif
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Par défaut
    même si ça ne reponds pas à ton besoin, voici comment on met à jour un tableau.
    concernant ton problème, je ne sais pas

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    <button (click)="click1()">click1</button>
    <button (click)="click2()">click2</button>
    ...
    ...


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
     
    import {Component, OnInit, ViewChild} from '@angular/core';
    import {MatPaginator} from '@angular/material/paginator';
    import {MatSort} from '@angular/material/sort';
    import {MatTableDataSource} from '@angular/material/table';
     
    /**
     * @title Table with pagination
     */
    @Component({
      selector: 'table-pagination-example',
      styleUrls: ['table-pagination-example.css'],
      templateUrl: 'table-pagination-example.html',
    })
    export class TablePaginationExample implements OnInit {
      displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
      dataSource = new MatTableDataSource<any>();
     
      @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
     @ViewChild(MatSort, { static: true }) sort: MatSort;
     
      ngOnInit() {
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      }
     
     click1() {
        this.dataSource = new MatTableDataSource<any>(ELEMENT_DATA1);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      } 
     
      click2() {
        this.dataSource = new MatTableDataSource<any>(ELEMENT_DATA2);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      } 
    }
     
     
     
    const ELEMENT_DATA1: any[] = [
      {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
      {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
      {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
      {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
      {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
      {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
      {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
      {position: 11, name: 'Sodium', weight: 22.9897, symbol: 'Na'},
      {position: 12, name: 'Magnesium', weight: 24.305, symbol: 'Mg'},
      {position: 13, name: 'Aluminum', weight: 26.9815, symbol: 'Al'},
      {position: 14, name: 'Silicon', weight: 28.0855, symbol: 'Si'},
      {position: 15, name: 'Phosphorus', weight: 30.9738, symbol: 'P'},
      {position: 16, name: 'Sulfur', weight: 32.065, symbol: 'S'},
      {position: 17, name: 'Chlorine', weight: 35.453, symbol: 'Cl'},
      {position: 18, name: 'Argon', weight: 39.948, symbol: 'Ar'},
      {position: 19, name: 'Potassium', weight: 39.0983, symbol: 'K'},
      {position: 20, name: 'Calcium', weight: 40.078, symbol: 'Ca'},
    ];
     
    const ELEMENT_DATA2: any[] = [
      {position: 1, name: 'Hydrogen2', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium2', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium2', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium2', weight: 9.0122, symbol: 'Be'},
      {position: 5, name: 'Boron2', weight: 10.811, symbol: 'B'},
    ];


    j'ai vérifié, le tableau et les fonctionnalités de pagination... fonctionne

  15. #15
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    Non mais le but de la réponse c'est de répondre à un besoin
    La l'information proposée n'est pas du tout en rapport avec ce que j'ai besoin...

    Si je comprends bien en fait tout le monde(dizaines de pages web inclues) sait afficher un tableau au chargement d'une page, mais personne ne sait l'afficher juste après une selection d'un bouton.. c'est juste ridicule.. en PHP et JS je l'ai fais en 5 minutes chronos...
    Là en Angular, je n'ai aucun idée de comment on fait cela... et le web ne propose que des exemples basiques de mise en place..

  16. #16
    Membre extrêmement actif
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Par défaut
    point (1)


    je te cite:
    mais la table ne se remplit pas car je ne vois pas comment initialiser la table ou la remplir une fois le get récupéré.

    VOICI comment on " initialiser la table ou la remplir "

    c'est un exemple de code qui permet d'initialiser le datTable non ? à moins que je suis devenu un gros CON qui ne comprends rien
    tu as déjà une petite partie de resolu, non ?




    DONC VOICI COMMENT ON INITIALISE UNE TABLE !!!!!!!!!!!!!!
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
        this.dataSource = new MatTableDataSource<any>(ELEMENT_DATA1);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    ELEMENT_DATA1 EST bien sur le resultat du GET... il faut que tu l'adapte




    si tu ne sais pas comment faire:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    this.getAllServices(namespace).subscribe( (res) => { 
        this.dataSource = new MatTableDataSource<any>(res);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    });


    et donc ça REPOND à ta question !

  17. #17
    Membre extrêmement actif
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Par défaut
    point (2)

    je te cite: "Une fois le namespace trouvé, l'utilisateur clique dessus, par exemple "monnamespace"."

    ça veut dire que là ou tu fou ce code quand tu clique depuis il envoi le namespace

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    ...... à mettre au bon endroit dans une balise du HTML .......    (click)="selection(option.namespace)">

    comme ça
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    selection(namespace) {
     
    // je récupère les données correspondant à namespace
    // et je met à jour le dataTable
     
    }

    (1) le principe de la mise à jour du tableau -> FAIT
    (2) le principe de l'action à faire suite au choix de l'utilisateur -> FAIT

    à toi d'adapter ces 2 principes à ton code

  18. #18
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    Alors le principe de sélection de l'utilisateur je l'ai déja depuis le premier post.
    En suivant ce que tu me dis j'en arrive à ça :

    Code angular : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
     dataSource = new MatTableDataSource<any>();
    ...
    ...
    ngOnInit() { 
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;    
      }
    ...
    ...
    getServices(namespace){   
        this.dataSource = new MatTableDataSource<any>(this.dataService.getAllServices("services")); //Problème
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort; 
      }

    Le this.dataService.getAllServices("services") est en erreur :
    Argument of type 'Observable<any[]>' is not assignable to parameter of type 'any[]'.
    Type 'Observable<any[]>' is missing the following properties from type 'any[]': length, pop, push, concat, and 25 more.

    Ma méthode getAllServices est la suivante :
    Code angular : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    public getAllServices(namespace) : Observable<any> {
        return this.httpClient.get<any[]>(this.REST_API_SERVER_BASE_LINK + '/' + namespace).pipe(tap(data => this.data = data));
      }

    En enlevant le Observable<any> j'ai le même résultat

  19. #19
    Membre extrêmement actif
    Avatar de dukoid
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2012
    Messages
    2 100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2012
    Messages : 2 100
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
        avec:      this.dataSource = new MatTableDataSource<any>(this.dataService.getAllServices("services"));
     
    public getAllServices(namespace) : Observable<any> {
        return this.httpClient.get<any[]>(this.REST_API_SERVER_BASE_LINK + '/' + namespace).pipe(tap(data => this.data = data));
      }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    this.dataService.getAllServices("services").subscribe( (res: any) => {
      // res   est donc les données
    });
    explication:
    comme tu peux le voir, getAllServices(namespace) : Observable<any>
    la fonction est un observable, il faut donc souscrire pour obtenir le resultat. c'est le prinicpe d'un observable

    à savoir:
    par exemple, si on faisait ça dans le HTML

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    {{ dataService.getAllServices(namespace) | async }}
    ça fonctionne car async veut dire qu'angular souscrit automatiquement et recupere les données.
    async permet de faire proprement un subscribe sans pourrir le code le HTML
    mais c'est juste pour information..


    dans notre code on doit le faire, on doit souscrire
    donc faut faire comme j'avais indiqué dans mon message précédent au point (1):

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    selection(namespace) {
     
      // je récupère les données correspondant à namespace
      // et je met à jour le dataTable
    
    
      this.dataService.getAllServices(namespace).subscribe( (res: any) => {      // res contient les données renvoyé par le get
        this.dataSource = new MatTableDataSource<any>(res);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      });
    }

  20. #20
    Membre confirmé
    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Novembre 2017
    Messages
    124
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Novembre 2017
    Messages : 124
    Par défaut
    Merci pour l'explication.
    Par contre j'arrive à l'afficher de cette manière :

    Code angular : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
     
    <ng-container *ngFor="let service of dataSource.data">  // avec le .data on à les données, sans on a rien
            {{service|json}}
            <hr>
          </ng-container>


    Par contre avec le tableau, Angular me renvoie une erreur ici "[dataSource]="dataSource" -> Can't bind to 'dataSource' since it isn't a known property of 'table'.



    Autre question : Pourquoi pour la récupération des namespaces je peux me contenter de | async mais pas pour les services ? ( il parait que subscribe peut engendrer des memory leaks.. donc c'est pour cette raison que je passais par async)
    En clair pourquoi dans ce cas là on doit souscrire ? J'ai bien compris que c'est un Observable mais on peut pas s'en débarasser pour faire avec async ?

+ Répondre à la discussion
Cette discussion est résolue.
Page 1 sur 2 12 DernièreDernière

Discussions similaires

  1. afficher une image d'extention.mat
    Par eviasra dans le forum Images
    Réponses: 17
    Dernier message: 20/06/2012, 11h50
  2. afficher une select
    Par peligrosa dans le forum Langage
    Réponses: 1
    Dernier message: 31/05/2012, 13h02
  3. [WD14] afficher une selection dans une table
    Par stefano dans le forum WinDev
    Réponses: 2
    Dernier message: 27/11/2010, 00h17
  4. Afficher une selection
    Par mouvma dans le forum Servlets/JSP
    Réponses: 5
    Dernier message: 04/07/2007, 11h39
  5. [MySQL] Afficher une selection d'enregistrement sur plusieurs pages
    Par largolgd dans le forum PHP & Base de données
    Réponses: 12
    Dernier message: 09/03/2006, 22h20

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo