我在angular—project中使用react 式表单,我使用mat—country—select在子FormComponent中的select中显示国家.
<mat-select-country class="full-width"
[formControl]="form.controls.country"
[required]="true"
appearance="outline"
[itemsLoadSize]="0"
[value]="DEFAULT_COUNTRY"
label="Choose country">
</mat-select-country>
我试图使模式对话窗口更新一个播放器在父Playerupet,有这样的 struct 如下所示.
export interface Player extends BaseResponse {
lastName: string;
firstName: string;
dateOfBirth: Date;
country: string;
height: number;
weight: number;
position: string;
jerseyNumber: number;
teamName: string;
teamId?: string | null;
photoPath?: string | null;
}
在PlayerComponent中,在打开更新对话框窗口之前,我应该初始化表单并将表单传递给我FormComponent
export class PlayersComponent implements OnInit {
countries: Country[] = COUNTRIES;
playerActionsForm!: FormGroup<PlayerActionsForm>;
fillUpdatePlayerForm(player: Player) {
this.playerActionsForm.controls.id.setValue(player.id);
this.playerActionsForm.controls.firstName.setValue(player.firstName);
this.playerActionsForm.controls.lastName.setValue(player.lastName);
this.playerActionsForm.controls.birthDay.setValue(player.dateOfBirth);
const country = this.countries.find(
(country) => country.name === player.country,
);
this.playerActionsForm.controls.country.setValue(country ? country : null);
this.playerActionsForm.controls.height.setValue(player.height);
this.playerActionsForm.controls.weight.setValue(player.weight);
this.selectTeams$
.pipe(
map((teams) => teams?.find((team) => team.id === player.teamId)),
take(1),
untilDestroyed(this),
)
.subscribe((team) => {
this.playerActionsForm.controls.team.setValue(team ? team : null);
});
this.playerActionsForm.controls.jerseyNumber.setValue(player.jerseyNumber);
this.playerActionsForm.controls.position.setValue(player.position);
this.playerActionsForm.controls.experiences.setValue([]);
}
initializeActionsForm() {
this.playerActionsForm = new FormGroup<PlayerActionsForm>({
id: new FormControl(''),
firstName: new FormControl('', [
Validators.required,
Validators.pattern(NAME_PATTERN),
]),
lastName: new FormControl('', [
Validators.required,
Validators.pattern(NAME_PATTERN),
]),
birthDay: new FormControl(null, [
Validators.required,
dateValidator(moment().subtract(18, 'years').toDate(), 'max'),
]),
country: new FormControl(null, Validators.required),
height: new FormControl(1.01, [
Validators.required,
Validators.min(1.01),
]),
weight: new FormControl(50.01, [
Validators.required,
Validators.min(50.01),
]),
team: new FormControl(null),
position: new FormControl('', Validators.required),
jerseyNumber: new FormControl(0, [
Validators.required,
Validators.min(0),
]),
experiences: new FormArray<FormGroup<PlayerExperienceForm>>([]),
});
}
ngOnInit(): void {
this.initializeActionsForm();
}
我try 使用viewChild来获取mat—country—select [Country]的Input属性,但它不起作用.现在我使用了我的预定义数组COUNTRIES,它是手工创建的.但我需要的解决方案,可以很容易地得到某个国家的名称,而不需要手动创建常量