Angular JS:在点击mat-select后显示mat-option的值



下午好!

这些天我一直在做一个基于口袋妖怪的项目。

我现在要解决的问题是能够在点击相应的垫子选择后显示垫子选项。

获取训练师名称数组和口袋妖怪数组的函数(在service.ts上)

getTrainersNames(): Observable<Array<string>>{
return this.http.get<Trainer[]>(`${this.apiUrl1}`).pipe(
map((entrenadores: Trainer[]) => {
return entrenadores.map((entrenador: Trainer) => entrenador.fullName);
})
);
}
getPokemonsOfATrainer(nombreEntrenador: string): Observable<Array<Pokemon[]>> {
return this.http.get<Trainer[]>(`${this.apiUrl1}?fullName=${nombreEntrenador}`).pipe(
map((entrenadores: Trainer[]) => {
return entrenadores.map((entrenador: Trainer) => entrenador.pokemons);
})
);
}

订阅口袋妖怪和训练师名称的函数,以及将训练师名称分配给getPokemonsOfATrainer函数(controller.ts)的函数

// INSIDE ngOnInit
this.obtainData.getTrainersNames().subscribe({
next: (nombres: string[]) => {
this.trainerNames = nombres
},
error: (err: Error) => console.log('Hubo un error en el observable '),
complete: () => {
console.log('Observer got a complete notification')
}, 
});
this.obtainData.getPokemonsOfATrainer(this.assignTrainerName()).subscribe( {
next: (pokemones: Pokemon[][]) => this.pokemons = pokemones[0],
error: (err: Error) => console.log('Hubo un error en el observable '),
complete: () => console.log('Observer got a complete notification'), 
});
// INSIDE ngAfterViewInit
assignTrainerName() {
// Get the selected value from the mat-select element
const selectedValue = this.attacksForm.controls['trainerName'].value;
// Check if the selected value is in the this.trainerNames array
const selectedTrainer = this.trainerNames.find(name => name === selectedValue);
console.log(selectedTrainer);
// If the selected value is in the array, assign it to this.trainerName
if (selectedTrainer) {
this.trainerName = selectedTrainer;
}
return this.trainerName;
}

最后是所需的mat-select:

<!--INSIDE a form-->
<mat-form-field appearance="standard">
<mat-label>Selecciona un pokemon</mat-label>
<mat-select matNativeControl formControlName="pokemonName" #matSelect>
<mat-option *ngFor="let pokemon of pokemons" [value]="pokemon.name">
{{pokemon.name}}
</mat-option>
</mat-select>
</mat-form-field>

如何显示垫子选项的值?

提前感谢!

组件的OnInit方法

this.attacksForm.controls['trainerName'].valueChanges.subscribe((x)=>{
this.obtainData.getPokemonsOfATrainer(this.assignTrainerName()).subscribe( {
next: (pokemones: Pokemon[][]) => this.pokemons = pokemones[0],
error: (err: Error) => console.log('Hubo un error en el observable '),
complete: () => console.log('Observer got a complete notification'), 
});
})

添加以上行代码,一旦trainerName的值改变,则调用getPokemonsOfATrainer获取数据&集。

最新更新