Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get model by html element in angular2

I need to access the model by the html element in angular2. In my case I use ng2-dragula to perform drag and drop and its service only has access to the html elements that are dragged. And I need to update the corresponding model of the element. Heres the issue at github.

like image 467
Yaroslav Yakovlev Avatar asked Apr 15 '16 12:04

Yaroslav Yakovlev


1 Answers

You can get the model of your item by searching for the index of the element in the elementList provided by the arguments of the subscription.

dragulaService.drop.subscribe(e => this.onDrop(e.slice(1)));

See?

UPDATE: Simplification (Thanks to Dracco)

private onDrop(args) {

    let [e, el] = args; //element, elementList
    let i = el.children.indexOf(e),
    item = i+1? this.items[i] : null;

    console.log(item); //The item
}

this.items is the variable where you store the list you pass to dragula. (e.g: [dragulaModel]="items").

I wish there was a simpler way. Tell me if you find one!

Old way:

private onDrop(args) {

    let [e, el] = args; //element, elementList
    let item;
    for(let i in el.children){
        if(el.children[i]==e){
            item = this.items[+i];
            break;                
        }
    }

    console.log(item); //The item
}

EDIT: the simplification had an error.

like image 82
Umagon Avatar answered Oct 18 '22 04:10

Umagon