Reputation: 419
I am following below jQuery example to convert it into Angular 2. Is there any way that How can i do it? Should i integrate jQuery in Angular 2 or any way in angular 2 to achieve this goal?
Example URL :
http://www.designchemical.com/blog/index.php/jquery/create-add-remove-select-lists-using-jquery/
Demo output : http://www.designchemical.com/lab/jquery/demo/jquery_create_add_remove_select_list.htm
Upvotes: 1
Views: 2935
Reputation: 202156
Based on the Mark Rajcok's answer:
You could implement this feature this way in the template:
<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 »</a>
<a (click)="removeElements()" id="btn-remove">« 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>
and in the component:
@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);
});
}
}
See this plunkr: https://plnkr.co/edit/5SQVErbgDaTyvHnjw7Wh?p=preview
Upvotes: 1
Reputation: 3851
A general rule of thumb: Do not mess around with the DOM when using Angular2, but only manipulate your data and let Ang2 do the rest using its data binding. This implies that I would never even consider using jQuery here.
The approach to take is:
Upvotes: 1