angular - Angular mat-select 在单击之前不可见,如何设置默认值
问题描述
我遇到了与制作 mat-selected 作品相关的树问题(请不要让我问 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>
我发现这个其他问题是第一个问题,但没有提供答案。
我也尝试了许多其他类似的答案,但没有运气(将浮动标签更改为始终并设置占位符值)
解决方案
您需要添加一个区域。区域提供跨异步任务持续存在的执行上下文。
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}`);
});
这应该可以解决您的问题。我无法通过测试来验证,因为我无法访问您的服务或代码游乐场链接来进行测试,但我已经在自己的类似场景中进行了测试。
推荐阅读
- ruby-on-rails - 无法使用 rails 更新编辑表单中的字段
- php - DataTables关于调整大小的响应问题
- python - 使用 python cv2 捕获外部 USB 网络摄像头的视频(在 Windows 上)
- racket - 获取列表列表的第二个元素作为列表列表
- javascript - AJAX 页面重定向正确。但是由于重定向传递的数据要刷新
- python-3.x - 3d 数组的 Numpy 乘法
- python - 使用每个元素 x 次将 python 数组映射到 x 倍长的数组
- nativescript - 在 Android 中发布构建问题 - Nativescript+ Angular
- android - 使用不同的资产构建多个应用程序,但使用相同的代码
- json - 在go中编码json标签