【问题标题】:Delete selected row index删除选定的行索引
【发布时间】:2018-05-24 12:58:34
【问题描述】:

大家好,我在删除问题表中的行表时遇到了一些麻烦。

这是我在 component.ts 中的 deleterowtable 函数

  deleteQuestions(questionsId: number) {

    this.questionerDetails.removeAt(1);

  }

这是我的组件 html

      <!--qeustion input-->
      <div formArrayName="questionerDetails" class="rap">
        <table id="myTable" align="center" class="table table-bordered">
          <tr><th>Questions</th><th>Actions</th></tr>
          <tr *ngFor="let questions of questionerDetails.controls; let i=index" [formGroupName]="i">
            <td><input style="width:100%;" formControlName="questionDetail" class="form-control" placeholder="type your questions here" /></td>
            <td align="center">

              <button (click)="deleteQuestions()" type="button" class="btn btn-success bc"><i class="fa fa-trash"></i></button>

            </td>

          </tr>
        </table>
      </div>

我的麻烦是我只能删除行表的最后一个索引或第一个索引。
示例:我有 5 行表 [0]、1、[2]、[3]、[4],我想删除编号 1 行被删除,然后我删除编号 [2] .所以行表有 [0],[4]。
选择行时如何删除行? 谢谢。

【问题讨论】:

  • 你错过了i里面的deleteQuestions()吗?
  • 是的,没错,我在 deleteQuestions(i) 中缺少 i

标签: angular


【解决方案1】:

您应该通过您的删除方法传递选定的索引

(click)="deleteQuestions(i)"

这一行给定了选定的索引let i=index

您的方法应该使用splice() 而不是removeAt()

deleteQuestions(index: number) {
    this.questionerDetails.splice(index, 1);

  }

【讨论】:

  • 好的,感谢您的回答,但我使用 removeAt 有效,我只在 deleteQuestions() 中缺少 i
  • @TM 你确定 removeAt 对你有用吗? stackoverflow.com/questions/50501112/…
  • 是的,可以在我的代码中使用 removeAt。如果我使用 .splice 得到错误“FormArray 类型上不存在属性切片”。
【解决方案2】:

首先。
您错过了deleteQuestion() 中的索引。这就是为什么您的 ts 找不到要删除的元素的索引的原因。您需要将其更改为deleteQuestion(i),这是您在表中的元素索引
第二。
您应该使用的方法是Slice(),而不是removeAt()。 这是它的文档。玩得开心
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2012-03-09
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多