首页 > 解决方案 > 推入 Angular 无法产生预期的结果

问题描述

我是角度学习推动力的新手。

我正在使用文本框将数据添加到表中。并通过单击按钮将模板引用传递给组件。

在组件中,我正在使用文本框的值和推送功能,但我无法检索数据

HTML 代码

<input type="text"  #userName >

<button (click)="addToTable(userName)">Add To Table</button>

<table>
    <tbody>
        <tr *ngFor="let u of users">
            <td>{{u.name}}</td>
        </tr>
    </tbody>
</table>

零件

import { Component, OnInit } from '@angular/core';

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

      selectedProduct=[];

      constructor() {
        this.selectedProduct;
      }

      addToTable(userName:any){
        this.selectedProduct.push(
          {name:userName.value}
          );
      }
      ngOnInit() {}
    }

标签: javascriptangulartypescript

解决方案


试试这个演示

export class AppComponent  {
  users = [
    {name: 'shan'}
  ]

  addToTable(data){
    this.users.push(
      {name: data.value}
    )
    data.value = ''
  }

}

您需要在users数组中推送值而不是selectedProduct


推荐阅读