首页 > 解决方案 > Angular mat-select 在单击之前不可见,如何设置默认值

问题描述

我遇到了与制作 mat-selected 作品相关的树问题(请不要让我问 3 个问题,因为它们都是相关的)

  1. 在我单击空白区域之前,该控件不可见
  2. 无论我选择什么,所选选项都没有显示(不保留)
  3. 也许第一个问题可以通过默认选择选项来解决

忽略按钮下方的红色消息只是提醒

在此处输入图像描述

当我单击空白处时,会出现选择选项。

在此处输入图像描述

做出选择后,控件处于无效模式

在此处输入图像描述

没有任何控制台/角度错误

这是组件

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-game-round',
  templateUrl: './game-round.component.html',
  styleUrls: ['./game-round.component.css']
})
export class GameRoundComponent implements OnInit {
  moves : string[] = [];
  selectedMove: string = 'Rock';

  currentRoundInfo = new FormGroup({
    moves: new FormControl('', [Validators.required]),
  });
  constructor(
    private router:Router) { }

  ngOnInit(): void {
    this.backService.getGameMoves()
      .subscribe((data: string[]) => {
        this.moves = data;
        //this.currentRoundInfo.setValue({moves : data}) ;
        console.log(`getGameMoves:${this.moves}`);
      });
      
    //trying to set a defult value
      this.currentRoundInfo.setValue({
        moves: 'Paper'
      });

  }

  moveSelected(move: string) {
    console.log("moveSelected:" + move) ;
    this.selectedMove = move ;
  }

  onSubmit() {
    console.log("next") ;
    
  }
}

这是HTML

<div class="full-width-centered">
  <form [formGroup]="currentRoundInfo" (ngSubmit)="onSubmit()">
    <div class="full-width" >
      <mat-form-field floatLabel="never" appearance="outline">
        <mat-label>Select your move:</mat-label>
        <mat-select [(value)]="selectedMove" formControlName="moves" placeholder="test placeholder" (selectionChange)="moveSelected($event.value)">
          <mat-option  *ngFor="let m of moves" [value]="m">
            {{m}}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <br>
    <div>
      <button type="submit">NEXT</button>
    </div>
  </form>
</div>

我发现这个其他问题是第一个问题,但没有提供答案。

mat-select 在我点击它之前不会显示

我也尝试了许多其他类似的答案,但没有运气(将浮动标签更改为始终并设置占位符值)

标签: angularangular-material

解决方案


您需要添加一个区域。区域提供跨异步任务持续存在的执行上下文。

import {Component, OnInit, NgZone} from '@angular/core';

 

constructor(
    private router: Router,
    private zone: NgZone
) { }

 

this.backService.getGameMoves()
  .subscribe((data: string[]) => {
    this.zone.run(() => {
        this.moves = data;
    });
    //this.currentRoundInfo.setValue({moves : data}) ;
    console.log(`getGameMoves:${this.moves}`);
  });

这应该可以解决您的问题。我无法通过测试来验证,因为我无法访问您的服务或代码游乐场链接来进行测试,但我已经在自己的类似场景中进行了测试。


推荐阅读