【问题标题】:How to retrieve and list selected option array angular typescript如何检索和列出选定的选项数组角度打字稿
【发布时间】:2020-07-02 04:36:23
【问题描述】:

嗨,我正在尝试检索所选选项的数组,目前只有公司名称在工作,因为我只能从 event.target.value 或 ngModel 获取一个值,我想知道该怎么做 如果你知道一个好的方法,我很想知道,如果你介意保持简单,我会很高兴,因为我还在学习:) (顺便说一句,数组来自数据库)

import { Component, OnInit } from '@angular/core';
import { Company } from '../_models/company';
import { CompanyService } from '../_services/company.service';
import { AlertifyService } from '../_services/alertify.service';


@Component({
  selector: 'app-company',
  templateUrl: './companies.component.html',
  styleUrls: ['./companies.component.css']
})
export class CompaniesComponent implements OnInit {

  companies: Company[];
  selectedCompany = [];

  constructor(private companyService: CompanyService, private alertify: AlertifyService) { }




  ngOnInit() {
    this.loadCompanies();

  }

  loadCompanies() {
    this.companyService.getCompanies().subscribe((companies: Company[]) => {
      this.companies = companies;
    }, error => {
      this.alertify.error(error);
    });
  }

  // selectedChangeHandler(event: any) {
  //   this.selectedCompany = event.target.value;
  // }

}
<div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
  <label for="">Select Company</label> <br>

  <select id="select" [(ngModel)]="selectedCompany"  >
    <option value="">Select</option>
    <option *ngFor="let value of companies" value="{{value.name}}">{{value.name}}</option>
    

  </select>
  <p>
    <span>
      You Selected:{{selectedCompany}}
    </span>
  </p>
</div>

<ul class="list-group list-group-flush">
  <li class="list-group-item">{{selectedCompany}}</li>
  <li class="list-group-item">Company address here</li>
  <li class="list-group-item">Company estimated revenue </li>
</ul>

【问题讨论】:

  • 你想在公司被选中时将其推送到 selectedCompany 吗?
  • 为什么要使用数组作为选定的公司?你可以只使用公司类型

标签: html angular typescript forms asp.net-web-api


【解决方案1】:

尝试将selectedCompany = [];的数据类型更改为selectedCompany:Company

然后你需要改变下面的行

 <option *ngFor="let value of companies" value="{{value.name}}">{{value.name}}</option>

<option *ngFor="let value of companies" [Value]="value">{{value.name}}</option>

【讨论】:

  • 是的,但现在是“[object Object]”
  • 我没听懂你? [object object] 是什么?
  • 尝试[value]而不是[ngValue]
  • 是的,但现在它的“[object Object]”没关系你为我解决了,我做了 selectedCompany.address :) 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2020-03-26
  • 2020-06-22
  • 2013-08-16
  • 2022-12-30
  • 2020-03-21
  • 2018-07-05
相关资源
最近更新 更多