我在下面的jQuery示例中将其转换为Angular 2.有什么方法可以做到这一点?我应该将AngQuery 2中的jQuery或角度2中的任何方式集成以实现此目标吗?
示例网址:
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
答案 0 :(得分:1)
一般的经验法则:当使用Angular2时,不乱用DOM,但仅操纵您的数据,让Ang2使用其数据绑定完成剩下的工作。这意味着我甚至不会考虑在这里使用jQuery。
采取的方法是:
答案 1 :(得分:1)
根据Mark Rajcok的回答:
您可以在模板中以这种方式实现此功能:
<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>
并在组件中:
@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