1

I got some problems with Angular2 creating custom directive with dynamic property binding.

In Angular2, I want to get template element before angular render it. But I still cannot find which method should I use.

I want to create a directive '<e-input></e-input>' and it will contain the attributes to be used by the function to create template as below:

<e-input data-id="myID"></e-input>

In angular 1, I used the following code to create it.

equip.directive("eInput",function(){ //<e-input>
        return{
            restrict: 'E',
            template: funciton(element){
                var xInput = document.createElement("INPUT");
                xInput.id = element[0].getAttribute("data-id");
                xInput.setAttribute("ng-model",xInput.id);

                return xInput;
            }
        }
    });

In above code, 'element[0]' is a template element which is '<e-input>'. I can get template elements by passing the variable 'element' so that I can manipulate it as I want before angular render it.

The result is:

<e-input data-id="myID">
     <input id="myID" ng-model="myID"/>
</e-input>

and the binding also worked.

I want to do the same in angular 2 but don't know how to do it. I don't know which variable to pass. Here is the code that I tried in Angular2 but no luck:

export class eInputBuilder{
    buildInput(xxxxxx){
        var xInput = document.createElement("INPUT");
        xInput.id = xxxxxx.getAttribute("data-id");
        xInput.setAttribute("[(ngModel)]",xInput.id);

        return xInput.outerHTML;
    }
}
@Component({
    selector:"e-input",
    template: eInputBuilder.prototype.buildInpuit(xxxxxx)
})
export class eInputComponent{
}

In code above, 'xxxxxx' is the variable I want to pass to buildInput() but I don't know what to pass.

Thanks in advance, T

tiberium
  • 13
  • 4

1 Answers1

0

That's not how Angular2 works. You can't get a reference to a components template before it is rendered. If you want to manipulated it use *ngIf or *ngFor to render it depending on the state in the class. Dynamically added HTML is not processed by Angular at all (), [], {{}} is just added as-is to the DOM and ignored by Angular for dynamically added HTML, also components or directives are not created even when selectors would match.

What also is supported is adding components dynamically like explained in Angular 2 dynamic tabs with user-click chosen components

@Component({
  selector: 'my-comp',
  template: `
  <input [id]="inputId" [ngModel]="model" (ngModelChange)="modelChange.emit($event)">
`)
export class SomeComponent {
  @Input() 
  inputId:string;

  @Input()
  data:string;

  @Output() 
  dataChange = new EventEmitter();
}

then you can use it like

<my-comp [(dataChange)]="parentData" [inputId]="'x123'"></my-comp>
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567