Search code examples
javascriptangularangular2-inputs

inject inputs into component constructor with es5 and es6


im trying to figure out how to get inputs using the es5 and es6 syntax in angular 2. i know its possible but the only documentation i can find on it uses the @ symbol which from what i understand is just syntax for the compiler but im not able to use a compiler so i have to write my code in just es5 and es6 no compiler no typescript whatsoever (believe me ive tried to get a typescript compiler on my computer but in my current environment im not able to.) does anyone know how to get inputs to work using just es5 and es6. here is what ive tried but i keep thinking i need some kind of injector for the input but i cant find any documentation on the injector aside from the typescript syntax

app.headerbtn = ng.core.Component({
    selector : 'header-btn',
    template : "<div class='headerbtn'>hello {{text}}</div>",
    inputs : ["text"]
}).Class({
    constructor : [function() {
        console.log(this);
    }],
    ngDoCheck : function() {
        this.text=this.text||'hi';
        console.log(this);
    }
});

then my html

<header-btn [text]='hello world'></header-btn>

the component is successfully bootstrapped and the it prints the constructor object to the console twice the problem being the first one is an empty object (which can make sense because it hasnt been initialized yet) but the second one has the text equal to "hi" meaning that the this.text is not defined before. or on any subsequent checks and the dom supports this as it prints hi into the {{text}}


Solution

  • The problem is that you use [text] (interpolation) with a value that isn't an expression. You would have the same problem with TypeScript. You could try this:

    <header-btn text="hello world"></header-btn>
    

    In the case of an expression:

    <header-btn text="someExpression"></header-btn>
    

    If you want to use [text], you need to define the expression with '':

    <header-btn [text]="\'hello world\'"></header-btn>
    

    Here is a plunkr describing this: https://plnkr.co/edit/cGmZgs9dCCyf8ICC8q9N?p=preview