首页 > 解决方案 > ngModel 不更新下拉菜单中的变量

问题描述

我正在尝试通过以下 HTML 代码更新我的打字稿中的变量“selectedValue”:

 <select class="form-control" [(ngModel)]="selectedValue"  >
            <option *ngFor="let item of clients" [value]="item" >{{item}}</option>

          </select>
          <p>here is the the item :  {{selectedValue}}</p>

在这里,列表客户端只是一个字符串列表。

我尝试将值更改为 ngValue,重新定位 <p> 标记并更改变量名称。

这是我的 ts 文件的样子:

export class BasicAccountComponent implements OnInit {
  accounts : Account[];
  clients: string [];
  selectedItem: string;
  columnDefs = [
    ...

  ];
  private defaultColDef;

  constructor(private accountService: AccountService) { 
    this.defaultColDef = {
      filter: true,
      width: 185,

    };
  }

  ngOnInit() {

    this.clients = [];
    this.selectedItem ='';
    //this.getAccountsByClient(this.selectedItem);
  }

  ngAfterViewInit() {
    // this.CalculatePageSize();
    this.getAccounts();
  }
  getAccounts() {
    this.accountService.getAccounts().subscribe(accounts => {
      this.accounts = accounts;
      this.accounts.forEach(account => {
        if (account != null){
          if (!this.clients.includes(account.client)){
            this.clients.push(account.client)
          }
      }
      })
      });

    }
  getAccountsByClient(client: string){
    this.accountService.getAccountsByClient(client).subscribe(accounts => {
      this.accounts = accounts;
      });
    }


}

变量 selectedValue 不会从空字符串更新。

标签: angular

解决方案


您在 html 中绑定了 selectedValue,但在 ts 文件中声明了 selectedItem。


推荐阅读