在Angular Bootstrap的ngb-tabset中获取Select DOM元素的值

时间:2019-04-17 16:03:36

标签: javascript angular

我在* ngFor循环(索引设置为idx)中具有以下DOM元素:

<div class="row" *ngFor="let item of myArray let idx=index">
    <select [id]="'myID' + idx"></select>
</div>

在我的组件中,我需要获取元素的值并尝试以下操作:

export class HelloComponent{
    constructor() {}

    ngAfterViewInit(){
       console.log((<HTMLSelectElement>document.querySelector('#myID0')).value);
    }
}

它引发以下错误:

ERROR TypeError: Cannot read property 'value' of null

当我执行console.log(document.querySelector('#myID0'))时,将元素打印出来。由于某些原因,我无法获得价值...

更新

我错过了我的选择位于ngb-tabset内的事实

您可以看到问题here的再现。完整的HTML代码是:

<ngb-tabset>
  <ngb-tab>
      <ng-template ngbTabTitle="">Tab</ng-template>
        <div class="row" *ngFor="let item of myArray let idx=index">
          <select [id]="'myID' + idx">
            <option>Hello</option>
          </select>
        </div>
      <ng-template ngbTabContent=""></ng-template>
  </ngb-tab>
</ngb-tabset>

2 个答案:

答案 0 :(得分:1)

在使用Angular时,我希望避免以这种方式访问​​DOM。您应该看看实现viewchildren。这应该为您提供所需的有关该元素的所有信息。自从您进行堆叠闪电射击以来,对不起的答案已经发生了巨大变化

public @ViewChildren('idx')public domElement: QueryList<any>; // be sure to import.

<select #idx> // in HTML

@ViewChildren可用于返回已标记元素的数组。这样做会如此。这将返回一个*ngFor元素数组。

然后您可以设置一些简单的方法来找到正确的元素。

const test = this.domElements.find(element => element.yourvalue === whatYouExpect);

答案 1 :(得分:0)

为select元素提供模板引用变量,并使用ViewChildren在组件中获取QueryList

<div class="row" *ngFor="let item of myArray let idx=index">
    <select [id]="'myID' + idx" #selectElements></select>
</div>
@ViewChildren('selectElements', { read: ElementRef })
selectElements: QueryList<ElementRef>;

请参见https://angular.io/api/core/ViewChildren