Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically append child from directive

I have a basic element:

<div>
    I'm a basic element
</div>

I want to create a directive that allows me to write this:

<div resizable-top>
    I'm a basic element
</div>

and renders this:

<div resizable-top>
    <div> drag me to resize element </div>
    I'm a basic element
</div>

So, basically I made a directive:

@Directive({
    selector: '[resizable-top]',
    host: {
        '(mousedown)':'onMouseDown()',
        '(mousemove)':'onMouseMove()',
        '(mouseover)':'onMouseOver()'
    }
})
export class ResizableDirective{

    constructor(private el:ElementRef){
    }

    onMouseDown(){
        //TODO
    }

    onMouseMove(){
        //TODO
    }

    onMouseOver(){
        //TODO
    }
}

problem is that I don't know how to create a child element using el and I want the events to be binded on child element, not on the actual element.

Since ElementRef.nativeElement is of type any I can't find out which methods/properties I can use to achieve what I want.

like image 880
Supamiu Avatar asked Apr 06 '16 09:04

Supamiu


1 Answers

el.nativeElement returns a HTMLElement if the selector contains a - otherwise an HtmlUnknownElement

The Angular way of doing it is to use the Renderer class in combination with ElementRef anyway.

constructor(private el:ElementRef, private renderer:Renderer){
}

and use the method it provides.

This keeps your application WebWorker and server-side-rendering safe.

like image 99
Günter Zöchbauer Avatar answered Oct 21 '22 09:10

Günter Zöchbauer