2017-10-04 81 views
7

在我的角度應用程序中,我有3個輸入說 - 代碼,名稱和價格。並且有一個表格顯示用戶選擇。 enter image description here角4:如何動態添加和刪除表中的行

當我點擊添加按鈕,從下拉菜單中選擇應該得到填充表的,

Product  Price  Action 
124578-ABC 100  <Delete Button> 

當我點擊刪除按鈕,相應的行應該被刪除。 我試着用jQuery來做這件事。但我想知道做這件事的角度。

+1

創建一個數組,其中新對象將增加被點擊後推,並使用表明,該陣列中的HTML * ngFor – porgo

+0

如果您使用角度,你擁有的jquery越少,它就越好。還有一點點的html代碼是可以接受的 – HaneTV

+0

利用porgo給予或者轉移到[reactive forms](https://rahulrsingh09.github.io/AngularConcepts/reactive) –

回答

10

嘗試這樣的:

在這個例子中,我只是使用文本框,而不是你的輸入類型

表像

<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> 

打字稿樣本:

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); 
    } 
} 
+0

@Poppy我希望這個答案將有助於你的問題。 – Chandru

+1

@Candru謝謝,它像一個魅力。但是,如果fieldArray初始爲空,以便存在一個空文本框,那麼可以做些什麼 –

-2

只需添加兩行相同的字段。一個與同場會避免fieldArray最初爲null和一個與同場的* ngFor這樣

<table> 

<tr> 
</tr> 

<tr *ngFor> 
</tr> 

</table> 
+0

歡迎使用Stack Overflow。請考慮其他現有和已接受的答案,並解釋如何添加新信息。 – Pac0