【问题标题】:I need to send values from my select options我需要从我的选择选项中发送值
【发布时间】:2019-10-04 18:15:55
【问题描述】:

我正在使用角度我想发送有关我在选择选项中选择的元素的信息。具体来说,我想将数据值发送到我的 product-form.component.ts 中的变量。 我尝试使用 ngModel,但我不断收到错误消息,说它无法识别 (click)=selectCategory1(category) 使用我正在为我的表单使用模板表单的函数,这可能是原因。您可以在以下位置查看我的代码: https://stackblitz.com/github/RashellSmith/Dashboard-FrontEnd

产品表单组件html

<div class="form-group">
    <label for="productCategory">Product Category</label>
    <select  [(ngModel)]="model.category" (click)=selectCategory1(category) name="category"  class="form-control" id="productCategory" (click)="value()">
        <option *ngFor="let category of categories" (click)=selectCategory1(category) data-value="{{category.category}}" id={{category.categoryName}} >{{category.categoryName}}</option>
    </select>
</div>

产品表单组件 ts

export class ProductFormComponent implements OnInit {

suppliers: Supplier[];
categories: Category[];
value: number;

model = new Newproduct("name",new Category( this.value,"name"),66,33,true,new Supplier(null,null),76);
selectCategory1(Category){
  console.log(Category);
}
submitted = false;
get diagnostic() { return JSON.stringify(this.model); }

onSubmit() { this.submitted = true; }

  constructor(private supplierService: SupplierService,private categoryService: CategoryService) { }

  ngOnInit() {
    this.supplierService.getAll().subscribe(data => {
      this.suppliers = data;
    });

    this.categoryService.getAll().subscribe(data => {
      this.categories = data;
    });
  }
}

【问题讨论】:

  • 你能创建一个 stackblitz/plunkr 以便调试吗?

标签: javascript angular typescript


【解决方案1】:

你肯定是想把事情复杂化。您需要将一个简单的(change) 方法绑定到您的选择列表,该方法将在值更改时触发。您可以使用模板引用变量将值传递给此函数

<Select #select (change)="SelectChanged(select.value)">

或者您可以绑定[(ngModel)] 指令并直接在(change) 上的组件类中访问它

一个示例模板代码:

<select [(ngModel)]="selectedOption" (change)="GetSelectedValue(selectedOption)">
    <option *ngFor="let option of options" [ngValue]="option">{{option}}</option>
</select>

组件类看起来像

GetSelectedValue(val) {
    //do something with val
}

Stackblitz:https://stackblitz.com/edit/angular-r4d7ul

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多