Angular 4:如何动态添加和删除表中的行

Pop*_*ppy 17 angular

在我的角度应用程序中,我有3个输入说 - 代码,名称和价格.并且有一个表格显示用户选择. 在此输入图像描述

当我点击添加按钮时,下拉列表中的选择应该填充到表格中,

Product     Price      Action
124578-ABC  100        <Delete Button>
Run Code Online (Sandbox Code Playgroud)

当我单击删除按钮时,相应的行应该被删除.我尝试使用jquery这样做.但我想知道做角色的方式.

Cha*_*dru 43

试试这样:

在这个例子中,我只使用了文本框而不是输入类型

表喜欢

<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>Code</th>
            <th>Name</th>
            <th>Price</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let field of fieldArray; let i = index">
            <td>
                <input [(ngModel)]="field.code" class="form-control" type="text" name="{{field.code}}" />
            </td>
            <td>
                <input [(ngModel)]="field.name" class="form-control" type="text" name="{{field.name}}" />
            </td>
            <td>
                <input [(ngModel)]="field.price" class="form-control" type="text" name="{{field.price}}" />
            </td>
            <td>
                <button class="btn btn-default"  type="button" (click)="deleteFieldValue(i)">Delete</button>
            </td>
        </tr>
        <tr>
            <td>
                <input class="form-control" type="text" id="newAttributeCode" [(ngModel)]="newAttribute.code" name="newAttributeCode" />
            </td>
            <td>
                <input class="form-control" type="text" id="newAttributeName" [(ngModel)]="newAttribute.name" name="newAttributeName" />
            </td>
            <td>
                <input class="form-control" type="text" id="newAttributePrice" [(ngModel)]="newAttribute.price" name="newAttributePrice" />
            </td>
            <td>
                <button class="btn btn-default" type="button" (click)="addFieldValue()">Add</button>
            </td>
        </tr>
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

打字稿样本:

export class Component {
    private fieldArray: Array<any> = [];
    private newAttribute: any = {};

    addFieldValue() {
        this.fieldArray.push(this.newAttribute)
        this.newAttribute = {};
    }

    deleteFieldValue(index) {
        this.fieldArray.splice(index, 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Candru谢谢,它就像一个魅力.但是如果fieldArray最初为null,那么可以做什么,以便行中存在空文本框 (3认同)