如何在Angular中选择组合框数据之前禁用按钮

时间:2019-01-27 18:14:45

标签: html angular

我有一个简单的模板,其中包括一个组合框,一个按钮和一个表格。 我想做的是,如果未选择组合框值,则按钮不可单击,并且在选择此按钮后将调用服务方法,获取雇主详细信息,此后该表将变为可见(在选择组合框值之前该表将不可见)然后单击按钮。) 我的代码是:

 <mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayoutGap="30px">

          <mat-form-field fxFlex="30%">
            <mat-select placeholder="Choose Employer"
                        [(ngModel)]="customModel"
                        #activeEmployers="ngModel"
                        required>
              <mat-option *ngFor="let emp of employerList" [value]="emp.displayName">{{emp.displayName}}
              </mat-option>
            </mat-select>
          </mat-form-field>
        </mat-card-content>
        <mat-card-actions>
          <button type="button" class="get-button" (click)="getEmployers()">
            GET DETAILS
          </button>
        </mat-card-actions>
      </mat-card>

      <mat-card>
        <mat-card-content>
          <mat-table #table [dataSource]="employerList">
            <!-- table rows -->

            <mat-header-row *cdkHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row class="table-row" *cdkRowDef="let config; columns: displayedColumns;"></mat-row>

          </mat-table>
        </mat-card-content>
      </mat-card>

此模板正在运行,但是是静态的,默认情况下所有组件都是可见的。我该如何实现上面提到的功能。

注意:所有这些元素都在ts文件的同一组件中。因此,没有亲子关系等等。

1 个答案:

答案 0 :(得分:2)

我建议以下内容:

在选择元素中,使用change伪指令。如果发生更改,将触发方法onSelection()。该方法将布尔值selectionFired设置为true。 如果发生这种情况,将启用该按钮。 [disabled]="!selectionFired"

如果单击按钮,则布尔值buttonClicked设置为true,这将使表格出现。 *ngIf="buttonClicked"

<mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayoutGap="30px">

      <mat-form-field fxFlex="30%">
        <mat-select placeholder="Choose Employer"
                    [(ngModel)]="customModel"
                    #activeEmployers="ngModel"
                    (change)="onSelection()"
                    required>
          <mat-option *ngFor="let emp of employerList" [value]="emp.displayName">{{emp.displayName}}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </mat-card-content>
    <mat-card-actions>
      <button type="button" class="get-button" [disabled]="!selectionFired" (click)="getEmployers()">
        GET DETAILS
      </button>
    </mat-card-actions>
  </mat-card>

  <mat-card>
    <mat-card-content>
      <mat-table *ngIf="buttonClicked" #table [dataSource]="employerList">
        <!-- table rows -->

        <mat-header-row *cdkHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row class="table-row" *cdkRowDef="let config; columns: displayedColumns;"></mat-row>

      </mat-table>
    </mat-card-content>
  </mat-card>

在您的TypeScript文件中

  protected selectionFired: boolean = false;
  protected buttonClicked: boolean = false;

  protected onSelection(): void {
      this.selectionFired = true;
  }

  protected getEmployers(): void {
      this.buttonClicked = true;
  }