代码之家  ›  专栏  ›  技术社区  ›  Roddy of the Frozen Peas

动态添加的hintLabel on mat form字段仅在组件接收到焦点后才可见

  •  0
  • Roddy of the Frozen Peas  · 技术社区  · 7 年前

    我有两个选择框。在第一个选择框中选择值时,将调用服务器以填充第二个选择框。由于我无法控制的原因,第二次调用需要约10秒的时间,因此我想显示一个类似“请稍候,从服务器获取XYZ”的提示

    显示 直到收到焦点为止(如果我尝试将提示放在第一个框中,它会立即显示提示,因为它已经具有焦点。)

    组件ts:

    @ViewChild("otherSelect")
    secondSelect: MatFormField;
    
    onFirstThingSelect(event: MatSelectChange ) {
     this.secondSelect.hintLabel = "Please wait, loading...";
     // expensive/slow call to populate secondSelect goes here
    }
    

    <mat-form-field #firstSelect>
      <mat-select placeholder="First Thing" (selectionChange)="onFirstThingSelect($event)">
        <mat-option *ngFor="let first of firstThings$ | async" [value]="first">
          {{first}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    
    <mat-form-field class="col-md-4" #otherSelect>
      <mat-select placeholder="Second Thing">
        <mat-option *ngFor="let second of secondThings$ | async" [value]="second">
          {{second}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    

    工作人员突击检查: https://stackblitz.com/edit/angular-fkjd8m-qm8mxp

    显然,这不是matHint(或hintLabel)最初的用意。但是,在填充第一个select之后,如何使提示针对第二个select显示?我必须为实际的第二个“选择”下拉列表添加ViewChild并强制聚焦到它上吗?

    3 回复  |  直到 7 年前
        1
  •  2
  •   G. Tranter    7 年前

    hintLabel @输入,将其绑定到变量并动态设置变量内容:

    <mat-form-field class="col-md-4" [hintLabel]="hintLabel">
      <mat-select placeholder="Second Thing">
        <mat-option *ngFor="let second of secondThings$ | async" [value]="second">
          {{second}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    
    
    hintLabel = '';
    
    onFirstThingSelect(event: MatSelectChange ) {
      this.hintLabel = "I should become visible when First Thing is selected.";
    }
    
        2
  •  1
  •   Eliseo    7 年前

    为什么不使用“占位符”。 您可以在第二件事中使用“tap”来显示不同的值。如果this.secondThing返回空值是因为正在加载数据,否则将显示类似“Select Option”的消息。

    看见 your forked stackblitz

    重要的部分是:

    this.secondThings$ = this._seconds.asObservable().pipe(tap((res) => {
          if (!res)
            this.secondPlaceHolder.placeHolder = "Loadding data...";
          else
            this.secondPlaceHolder.placeholder = "Select Option.";
    
        }))
    

    发生更改时,首先发送一个null

      onFirstThingSelect(event: MatSelectChange) {
        this._seconds.next(null); //<--send a null before loading the data
        setTimeout(() => {
          this._seconds.next(["AA", "BB", "CC"]);
        }, 2000)
      }