Angular 2 surrounding an input tag with div via directive -


i'm trying create directive takes input element , surrounds div, example, html like:

<input type="text" class="form-control" inputwrapper /> 

and desired outcome:

<div class="input-wrapper">     <input type="text" class="from-control" /> </div> 

directive:

@directive({     selector: '[inputwrapper]' }) export class inputwrapperdirective {     constructor(private viewcontainerref: viewcontainerref, private elementref: elementref) {         // goes here?     } } 

here how directive. code uses renderer2, think angular 4. same thing can achieved renderer (which marked deprecated now)

i did work in ngafterviewinit method. may use constructor instead.

import { directive, renderer2, elementref, afterviewinit } '@angular/core'  @directive({     selector: '[inputwrapper]' }) export class inputwrapperdirective implements afterviewinit {     constructor(private _renderer:renderer2, private _el: elementref) {      }      ngafterviewinit() {         // parent of original input element         var parent = this._el.nativeelement.parentnode;          // create div         var divelement = this._renderer.createelement("div");          // add class "input-wrapper"         this._renderer.addclass(divelement, "input-wrapper");          // add div, before input         this._renderer.insertbefore(parent, divelement, this._el.nativeelement);          // remove input         this._renderer.removechild(parent, this._el.nativeelement);          // remove directive attribute (not necessary, clean)         this._renderer.removeattribute(this._el.nativeelement, "inputwrapper");           // re-add inside div         this._renderer.appendchild(divelement, this._el.nativeelement);      }  } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -