在这里,我试图通过点击按钮时的模板引用变量发送数据,但我得到了错误Cannot read property 'value' of undefined
pfb我的代码:
.ts代码

sample = "Angular";

data = [
  { id: 1, name: "Mr. Nice" },
  { id: 2, name: "Narco" },
  { id: 3, name: "Bombasto" },
  { id: 4, name: "Celeritas" },
  { id: 5, name: "Magneta" },
  { id: 6, name: "RubberMan" },
  { id: 7, name: "Dynama" },
  { id: 8, name: "Dr IQ" },
  { id: 9, name: "Magma" },
  { id: 10, name: "Tornado" }
];

check(ds) {
  console.log(ds.value);
}

.html代码
<div *ngFor="let x of data">
   <input type="text" id={{x.id}} name={{x.name}} [(ngModel)]="sample" #ds="ngModel">
</div>

<button type="button" (click)="check(ds)">Check</button>

最佳答案

你可以像下面这样试试,但这更复杂

<div *ngFor="let x of data">
    <input type="text" id={{x.id}} name={{x.name}} [ngModel]="sample" #ds>
</div>

<button type="button" (click)="check()">Check</button>

TS文件
@ViewChildren('ds') inps: QueryList<ElementRef>;

check() {
    console.log(this.inps);
    for (var x in this.inps) {
      if (x == "_results") {
        for (var i = 0; i < this.inps[x].length; i++) {
          console.log(this.inps[x][i].nativeElement.value)
        }
      }
    }
}

通过一些代码行,您可以实现您想要的
if (!this.inps[x][i].nativeElement.value) {
  this.inps[x][i].nativeElement.style.borderColor = "red";
}

也更新了stackblitz,请检查
更新的代码
check() {
  let checkids = [2, 3, 6];
  for (var x in this.inps) {
    if (x == "_results") {
      let id;
      for (var i = 0; i < this.inps[x].length; i++) {
        id = this.inps[x][i].nativeElement.getAttribute('id');
        if ((checkids.indexOf(+id) != -1) && !this.inps[x][i].nativeElement.value) {
          this.inps[x][i].nativeElement.style.borderColor = "red";
        }

      }
    }
  }
}

工作Stackblitz

关于angular - 无法使用 Angular 2+获取模板引用值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52440792/

10-12 06:37