lys1030
lys1030

Reputation: 283

Bind a DOM element in template

I have the following Component:

import {Component, OnInit} from 'angular2/core';
@Component({
    selector: 'test',
    template: `{{renderer.domElement}}`
})
export class TestComponent implements OnInit {
    renderer;    
    ngOnInit() {
        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setSize(300, 300);
        //document.body.appendChild(this.renderer.domElement);
    }
}

The {{}} property binding doesn't bind the DOM element to template. Using appendChild doesn't make the DOM up-to-date with the "renderer" variable. The only way I can think of is to read the text content of the DOM element and bind it, but I guess it's not the best approach. How should I do it?

Upvotes: 2

Views: 1093

Answers (3)

kemsky
kemsky

Reputation: 15279

{{}} curly braces are used for interpolation, your template effectively converted to renderer.domElement.toString().

You should change selector to '[test]' and use injected ElementRef to access ElementRef.nativeElement:

<canvas test></canvas>

Constructor:

this.renderer = new THREE.WebGLRenderer({canvas: elementRef.nativeElement});

Upvotes: 0

lys1030
lys1030

Reputation: 283

Finally got it work. Thanks for the help!

import {Component, ElementRef} from 'angular2/core';

@Component({
    selector: 'test',
    template: ''
})
export class TestComponent {

    el;

    constructor(public elementRef: ElementRef) {
        this.el = elementRef.nativeElement;
        this.renderer = new THREE.WebGLRenderer();
        this.el.appendChild(this.renderer.domElement);     
    }
}

Upvotes: 0

Gene
Gene

Reputation: 616

In Angular 1.XXX having a dynamic template is often not required and often makes for unreadable code. In your situation above replace the template with something like:

template: "<canvas class='threeEl'></canvas>"

Then add a constructor to your class to get the elementRef and use the canvas property when instantiating the WebGLRenderer():

export class TestComponent implements OnInit {
    el; 
    renderer;    
    constructor: [ng.core.ElementRef, function(elementRef) {
      el = elementRef.nativeElement;
    }]

    ngOnInit() {
        this.renderer = new THREE.WebGLRenderer({canvas: this.el});
        this.renderer.setSize(300, 300);
        //document.body.appendChild(this.renderer.domElement);
    }
}

Upvotes: 1

Related Questions