javascript - 使用 Angular 从下拉列表中获取选定的值

标签 javascript html angular typescript select

<tr (click)="onRowClick(myDropDownList.value)">
<td>
<select #myDropDownList (click)="$event.stopPropagation()" (change)="onChange($event.target.value)">
    <option *ngFor="let n of numbers" [value]="n">{{n}}</option>
</select>
</td>
</tr>

我试图从下拉列表中获取选定的值并将其分配给 onRowClick 函数。但由于某种原因,myDropDownList 总是显得未定义。我想知道这里可能会出什么问题。

最佳答案

在这种情况下使用 Forms 或 ngModel 。 使用表单

模板

<form [formGroup]="test">
        <div class="col-sm-6 form-group">
            <label>Industry</label>
            <tr (click)="onRowClick(myDropDownList.value)"> Click
                <td>
                    <select #myDropDownList class="form-control select" formControlName="Industry">
          <option [selected] = "true == true" [ngValue] = "0"> Please Select</option>
          <option *ngFor="let industry of industries"  [ngValue]="industry.id">{{industry.name}} </option>  
    </select>
                </td>
            </tr>
        </div>
    </form>

组件

export class AppComponent implements OnInit { 
  name = 'Angular 5';
  test:FormGroup;
  industries = [{id:1,name:"rahul"},{id:2,name:"jazz"}];

  ngOnInit(){
     this.test = new FormGroup({
      Industry:new FormControl('')
    });

    this.test.get('Industry').valueChanges.
    subscribe(data =>
      console.log(this.industries.filter(d =>  {return d.id == data}))
    );

  }

  onRowClick(value){
    console.log("called");
    alert(value);
  }

}

Working Example

关于javascript - 使用 Angular 从下拉列表中获取选定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47406659/

相关文章:

php - 当我在我的主页中单击我的链接时如何从另一个 php 文件调用模式

html - 将带有 html 标签的文本显示为 html

javascript - 正则表达式替换多个通配符在 PHP 中有效,但在 JavaScript 中无效

Angular 4 Date-Picker - 如何限制 future 和过去的日子

angular - 使用路由器的国际化 Angular 应用程序

javascript - Jquery: slideToggle() 多个 div 独立使用一个函数

javascript - 将连接的 JavaScript 字符串传递到 JQuery 变量中?

javascript - 吸气函数的速度与直接访问

javascript - 使用 d3.js 可视化数据组的数据技术

html - 无需表单发布即可触发 html5 验证