2016-04-26 7 views
1

私はそれをAngular 2に変換するためにjQueryの例の下に従っています。どのようにすればよいのですか?この目標を達成するために、角度2でのjQueryまたは角度2での任意の方法を統合する必要がありますか?このjQueryコードをAngular 2に変換するには?

例URL:

http://www.designchemical.com/blog/index.php/jquery/create-add-remove-select-lists-using-jquery/

デモ出力: http://www.designchemical.com/lab/jquery/demo/jquery_create_add_remove_select_list.htm

答えて

1

あなたは、このようテンプレートでこの機能を実現することができます。

<form> 
    <fieldset> 

    <select name="selectfrom" id="select-from" multiple size="5" (change)="changeSelectFrom($event.target.options)"> 
     <option *ngFor="#elt of selectFromValues" [value]="elt.value">{{elt.name}}</option> 
    </select> 

    <a (click)="addElements()" id="btn-add">Add &raquo;</a> 
    <a (click)="removeElements()" id="btn-remove">&laquo; Remove</a> 

    <select name="selectto" id="select-to" multiple size="5" (change)="changeSelectTo($event.target.options)"> 
     <option *ngFor="#elt of selectToValues" [value]="elt.value">{{elt.name}}</option> 
    </select> 

    </fieldset> 
</form> 

とコンポーネントで:

@Component({ 
    (...) 
}) 
export class App { 
    @ViewChild('select-from') selectFromElRef; 
    @ViewChild('select-to') selectToElRef; 

    constructor() { 
    this.selectFromValues = [ 
     { value: '1', name: 'Item 1' }, 
     { value: '2', name: 'Item 2' }, 
     { value: '3', name: 'Item 3' }, 
     { value: '4', name: 'Item 4' } 
    ]; 

    this.selectToValues = [ 
     { value: '5', name: 'Item 5' }, 
     { value: '6', name: 'Item 6' }, 
     { value: '7', name: 'Item 7' } 
    ]; 
    } 

    getSelectedElements(options, values) { 
    return Array.apply(null, options) 
     .filter(option => option.selected) 
     .map(option => { 
     return values.find((elt) => elt.value === option.value); 
     }); 
    } 

    changeSelectFrom(options) { 
    this.fromValues = this.getSelectedElements(options, this.selectFromValues); 
    } 

    changeSelectTo(options) { 
    this.toValues = this.getSelectedElements(options, this.selectToValues); 
    } 

    addElements() { 
    this.fromValues.forEach((elt) => { 
     this.selectToValues.push(elt); 
     let index = this.selectFromValues.findIndex((elt1) => elt1.value === elt.value); 
     this.selectFromValues.splice(index, 1); 
    }); 
    } 

    removeElements() { 
    this.toValues.forEach((elt) => { 
     this.selectFromValues.push(elt); 
     let index = this.selectToValues.findIndex((elt1) => elt1.value === elt.value); 
     this.selectToValues.splice(index, 1); 
    }); 
    } 
} 

このplunkrを参照してください。https://plnkr.co/edit/5SQVErbgDaTyvHnjw7Wh?p=preview

1

親指の一般的なルール:Angular2を使用するときにDOMと周りない混乱を行いますが、は唯一はあなたを操作しますAng2はデータバインディングを使用して残りの処理を行います。これは、ここでjQueryの使用を検討することさえないことを意味します。

取るべきアプローチがある:

  • があなたのコンポーネント(またはコンポーネントが使用しているサービス)にいくつかのデータストアを追加します。これは、2つのリストの2つの配列ほど簡単です。
  • 2つのフォーム要素がデータストアを使用して構築されるようにテンプレートを変更します。
  • ユーザーが2つのボタンのうちの1つを使用してアクションをトリガーすると、それに応じてデータストアを変更します。
  • それです。 Ang2はあなたのためにすべての仕事をします。マークRajcokの答えに基づいて
関連する問題