2017-10-09 35 views
1

我的表單中有一個輸入字段。如何將值從輸入字段存儲到臨時數組並將其顯示在Angular2的列表中?

  • 它是用於獲取聯繫人號碼
  • 用戶可以添加多個聯繫人號碼;因此代替使用的聯繫信息的多個字段我想使用一個單一的輸入字段
  • 每當用戶輸入數字和(的OnChange)事件的接觸應該以下面的列表的臨時數組和列表存儲。
  • 在該列表中,如果用戶希望他能刪除他補充說,如果他想

我增加了我的樣本代碼的接觸。我需要的要求。我試圖使用我的概念,但我陷入困境。

template.html

<div class="col-md-4"> 
     <div class="md-form"> 
     <i class="fa fa-mobile prefix" style="font-size: 46px; margin-top: -10px;"></i> 
     <input type="text" id="rec4" class="form-control" (change)="store()" ng-model="contact"> 
     <label for="rec4" class="">Contact Number</label> 
     </div> 
     </div> 

<ul> 
<li>{{data1}}></li><li><{{data2}}></li> 
<ul> 

test.ts

export class App { 

public contact:any[]; 

} 
    constructor() { 


    } 

} 

我的樣品Plunker code

+2

Hi Deepak。爲了幫助當前和未來的讀者,我在過去對您的帖子進行過多次編輯。一些相同的問題不斷出現;我想知道我是否可以向你提及他們,所以志願編輯的工作量較少?特別有兩件事:當提到你自己時(「我」),它總是大寫,沒有例外。另外,沒有必要在您的問題中添加「請幫助我」。讀者知道你需要幫助,所以這看起來像乞討。謝謝! – halfer

+1

@halfer:相信我會遵循這個程序(Y) –

回答

1

保持你的代碼的一些變化

  1. 設置本地模板變量輸入。
  2. 列表李和ngFor,不要忘了跟蹤與trackBy
  3. 將值設置爲 '' 進入後
  4. 沒有模型需要

HTML

<input type="text" id="rec4" #input class="form-control" (change)="store(input.value); input.value=''"> 
.... 
<ul> 
    <li *ngFor="let d of data; let i=index; trackBy: trackByFn"> 
    {{d}} 
    </li> 
<ul> 

打字稿:

store(newValue){ 
    this.data.push(newValue); 
    console.log(this.data) 
} 

DEMO

1

我克服了使用keyup.enter。基本上,只要你點擊ENTER(返回)鍵,該函數就會被調用。

您可以使用它像以下:

//template 
<input type="text" (keyup.enter)="store()" [(ng-model)]="contact"> 
<ul> 
    <li *ngFor="let c of contactList">{{c}} <button (click)="removeContact(c)">remove</button> </li> 
</ul> 


//.ts 
private contactList: Array<string> = []; 
public store(){ 
    this.contactList.push(contact) 
    this.contact = null; 
} 
public removeContact(number){ 
    //remove logic here... 
} 

這僅僅是一個例子牢記你的背景,你可以但使用它,你請。

+0

謝謝你給我的想法:) .. –

+0

永遠在這裏爲社區人! – imixtron

相關問題