изменить детали таблицы матов на основе раскрывающегося значения (JSON запрос POST) - PullRequest
0 голосов
/ 27 января 2020

нужна помощь по HTTP-запросу клиента с точки зрения angular из выпадающего списка, если я выберу любую страну, которую запрос должен отправить на сервер, используя метод отправки, и данные будут отображены в таблице Mat

происходит, у меня есть данные только для страны BEL для других стран, которых у меня нет, но если я выбрал другие страны, в это время также показывались данные о стране.

вот мой код для HTML

<div class="row greybg">
    <div class="col col-md-2">            
        <mat-form-field>
            <mat-label>Select Country</mat-label>
            <mat-select [(ngModel)]="selectedValue" name="countryList">
              <mat-option *ngFor="let country of countryList" [value]="country.countryCode">
                {{country.countryName}}
              </mat-option>
            </mat-select>
          </mat-form-field>
    </div>
    <div class="col col-md-7" style="margin-left:25px;">
        <button style="margin-top:5px;" type="button" class="btn" (click)="displayTable()">View</button>
    </div>
    <div class="col col-md-2">
        <mat-form-field >
            <input  matInput (keyup)="applyFilter($event.target.value)" type ="text" placeholder="Search by IBT Institution Name" >
            <mat-icon matPrefix>search</mat-icon>
        </mat-form-field> 
    </div>
</div>
<div class="row">
    <div style="width: 50%;float:left">
        <table  *ngIf="dataSource?.data?.length > 0" mat-table [dataSource]="dataSource" > 
            <!-- Site Number -->
            <ng-container matColumnDef="site">
                <th mat-header-cell *matHeaderCellDef > Site </th>
                <td mat-cell class="mat-cell" *matCellDef="let element"> {{element.siteNumber}}
                </td>
            </ng-container>
            <!-- IBT Details -->
            <ng-container matColumnDef="ibtInstitutionNamePIName">
                <th mat-header-cell *matHeaderCellDef > IBT - Institution Name / PI Name </th>
                <td mat-cell class="mat-cell" *matCellDef="let element"> {{element.ibtInstitutionName}} / {{element.ibtInvestigatorFullName}}                            
                </td>
            </ng-container>
            <ng-container matColumnDef="action">
                <th mat-header-cell *matHeaderCellDef></th>
                <td mat-cell class="mat-cell" *matCellDef="let element">
                    <a (click)="openDialog('selectCtms',element)"><span class="icon"><i class="fas fa-link"></i></span></a>
                </td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="columnsToDisplay;"></tr>
            <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
        </table >
    </div>
    <div style="width: 50%;float:right">
            <table *ngIf="dataSource1?.data?.length > 0" mat-table [dataSource]="dataSource1">
                <!--CTMS Details -->
                <ng-container matColumnDef="ctmsInstitutionNamePIName">
                    <th mat-header-cell *matHeaderCellDef> CTMS - Institution Name / PI Name</th>
                    <td mat-cell class="mat-cell" *matCellDef="let element">
                         <span *ngIf="!ctmsMatch">Match Sites</span>
                         <span *ngIf="ctmsMatch">{{element.ctmsInstitutionName}} / {{element.ctmsInvestigatorFullName}}</span>
                    </td>  
                </ng-container>
                <tr mat-header-row *matHeaderRowDef="columnCTMStoDiplay;"></tr>
                <tr mat-row *matRowDef="let row; columns: columnCTMStoDiplay;"></tr>
            </table> 
    </div>
</div>

Вот мой код для TS

      public dataSourceCountry = new MatTableDataSource<CountryMatch>([]);
      public columnsToDisplay: string[] = ['site', 'ibtInstitutionNamePIName','action'];
      public columnCTMStoDiplay: string[] = ['ctmsInstitutionNamePIName'];
      public countryTableDisplay = new MatTableDataSource<IbtList>([]);
      public cacheFullData =new MatTableDataSource<IbtList>([]);
      public matchsiteLabel: String;
      public ctmsMatch = false;
      constructor(private route: ActivatedRoute, private dataService: DataService,  private router: Router, public dialog: MatDialog) {

       }

      ngOnInit() {
            this.matchsiteLabel = "Match Sites"
            const routerSubscription = this.route.paramMap.subscribe(paramMap => {
              this.bcnumber = paramMap.get('bcnumber');
              //this.countryCode = paramMap.get('bcnumber');
            });
            this.unsubscribe.push(routerSubscription); 
              const countryListData = this.dataService.getcountryMatchDetails(this.bcnumber).subscribe(data => {  
              this.dataSourceCountry = new MatTableDataSource<CountryMatch>(data);
              this.countryList = data;  
              console.log(this.countryList);
          }); 

            this.unsubscribe.push(countryListData);
            const matchData = this.dataService.getIbtDetails(this.countryCode).subscribe(response => {  
            this.countryTableDisplay = new MatTableDataSource<IbtList>(response);    
            this.cacheFullData = new MatTableDataSource<IbtList>(response);
           }); 
          this.unsubscribe.push(matchData);
      }

  displayTable(){    
   if (this.selectedValue == "0")
      this.countryTableDisplay = this.cacheFullData;             
    else {
      const data = this.countryTableDisplay.data;
      this.dataSource.data = data;
      console.log(this.dataSource.data);
      this.dataSource1.data = data;
     }
   }

JSon

    {
  "bcNumber": "50209-01",
  "countryCode": "BEL  ",
},
{
  "bcNumber": "50209-01",
  "countryCode": "BEL  ",
  "statusFlag": "I"
},

Пожалуйста, дайте мне знать, что я делаю неправильно.

заранее спасибо

1 Ответ

0 голосов
/ 27 января 2020

Если вы пытаетесь отправить запрос на публикацию и обновить этот источник данных при изменении параметра в раскрывающемся списке, вы можете вызвать функцию для отправки запроса на отправку и обновить this.dataSource

Чтобы вызвать функцию при изменении выпадающего элемента в angular

Добавить событие изменения выбора выпадающего списка в HTML

<mat-select [(ngModel)]="selectedValue" name="countryList" (selectionChange)='updateData()'>
    <mat-option *ngFor="let country of countryList" [value]="country.countryCode">
                {{country.countryName}}
    </mat-option>
</mat-select>

Добавить updateData функция в вашем TS

updateData(){
    // your post api call to fetch data 
    // assigin the response data to your datasource
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...