Próbuję ustawić wartość domyślną dla mojego znacznika "select" w kanale 2 zgodnie z modelem
Oto mój kod:
HTML
<div>
<label>Agence: </label>
<select [(ngModel)]="candidat.agence">
<option *ngFor="let agence of agences" [ngValue]="agence">{{agence.nom}}</option>
</select>
</div>
SKŁADNIK
export class CandidatDetailComponent implements OnInit {
@Input()
candidat: Candidat;
agences: Agence[];
constructor(
private agenceService: AgenceService,
) {}
ngOnInit(): void {
this.agenceService.getAgences().then(agences => this.agences = agences);
}
}
AGENCJA
export class Agence {
id: number;
nom: string;
}
CANDIDAT
export class Candidat {
id: number;
nom: string;
agence: Agence;
}
Atrybuty candidat są pobierane z innego komponentu
Po wyświetleniu elementu div domyślna wartość agence.nom
nie jest ustawione
Czy ktoś ma pomysł? Dzięki !!!
Odpowiedzi:
2 dla odpowiedzi № 1Po pierwsze select
muszę mieć name
atrybut:
<select [(ngModel)]="candidat.agence" name="WHATEVER">
Na podstawie code
pokazano, powiązanie powinno się automatycznie ... może candidat.agence
ma trochę właściwość inna niż agence
(z agences
szyk).
W każdym razie, aby ustawić candidat
, możesz to zrobić:
ngOnInit(): void {
this.agenceService.getAgences().then(agences => this.agences = agences);
if (this.candidat && this.candidat.agence) {
this.candidat.agence = this.agences.find(agence => agence.name === this.candidat.agence.name);
}
}
0 dla odpowiedzi nr 2
Znaleziono brzydkie obejście:
ngOnChanges(): void {
if (this.candidat) {
for (let agence of this.agences) {
if (this.candidat.agence.nom == agence.nom) {
this.candidat.agence = agence;
}
}
}
Ustawiło to kandydaturę do obiektu określonego na liście
Czy istnieje lepszy sposób na zrobienie tego?