简体   繁体   中英

Angular - Bind Dropdown or select to API (database)

I was on a project with Angular and a backend.

If I enter a list in the ts file:

this.towns = [{
       code: '1',
       label: 'Paris'
   },
   {
       code: '0',
       label: 'Vancouver'
   }
 ];

I can display them in my html but not if I try to connect to a db:

<select  class="selectpicker dropdown mt-4 ml-3" id="town">
   <option *ngFor="let town of towns" [value]="town.id">{{town.name}}</option>
</select>

In my ts file, I tried:

export class TestComponent implements OnInit {
 
  form: FormGroup;
  towns: { id: number, name: string }[];
 
  constructor(
    private http: HttpClient
  ) { }
 
  towns: Town[];
  apiUrl = 'https://localhost:8000/api/';
 
  ngOnInit(): void {
    this.form = new FormGroup({
      town: new FormControl()
    });
    this.getTown();
  }
 
  onClickTown(): Observable<any> {
    console.log(this.form)
    return this.http.get(this.apiUrl + 'towns')
  }
 
  getTown() {
    this.http.get<any[]>(this.apiUrl + 'towns')
      .subscribe(data => {
        this.towns = data;
        console.log(data)
      });
  }
 
  postData() {
    console.log("data");
    this.http.post<any[]>(this.apiUrl, {}).
      subscribe(
        (data: any[]) => {
          // console.log(data);
        }
      )
  }

Did I forget a step? Thanks

This is because changes are not detected. You can try reinitializing the towns array so that Angular detects changes.

getTown() {
  this.http.get<any[]>(this.apiUrl + 'towns')
    .subscribe(data => {
      /* reinitialize the towns array */
      this.towns = [];
      /****/
      this.towns = data;
      console.log(data)
    });
}

Try the code below.

I've used the async pipe to iterate. (Notice you should return Observable for that) I've also used the ngValue attribute to bind to the form

HTML

<select formControlName="town">
  <option *ngFor="let town of towns | async" [ngValue]="town">{{town.name}}</option>
</select>

TS interface

exprot interface Town{
  id:number;
  name:string;
}

TS Component

export class TestComponent implements OnInit {

  form: FormGroup;
  towns:Observable<Town[]>;
  apiUrl:string = 'https://localhost:8000/api/';

  constructor(private http: HttpClient) { }

  ngOnInit(): void {        
    this.towns = this.http.get<Town[]>(this.apiUrl + 'towns');        
    this.form = new FormGroup({
      town: new FormControl()
    });
  }

I changed my getTown function to solve it and so my html:

  getTown() {
    this.townsObs = this.http.get<any[]>(this.apiUrl + 'towns').subscribe(data => {
        this.towns = data['hydra:member'];
        console.log(data['hydra:member'])
      });
  }

Thanks to you all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM