1

I would like to declare an attribute and assign a value to it in the component's HTML tag, like this:

<my-component my-attr="foo"></my-component>

Then I'd like to get the value of this attribute (my-attr) from inside my controller.

Is this possible using AngularJS 1.6 and TypeScript, and if yes how?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
luthien
  • 1,285
  • 3
  • 15
  • 26

2 Answers2

0

When defining the component, declare myAttr as a binding for the component. This way its value will be part of your controller.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
0

The attribute should be declared in the bindings:

app.component('myComponent', {
  ...
  bindings: {
    myAttr: '@'
  }
});

(Binding types: What is the difference between '@' and '=' in directive scope in AngularJS?)

The name of the attribute is normalized to camelCase and the value will be set on the controller instance as a property. So you might want to declare it accordingly on your controller type:

class MyComponentController
{
    myAttr: string;

    logAttribute()
    {
        console.log(this.myAttr);
    }
}
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Thanks for the fast answer. I am not sure I can do it like this with TypeScript, it seems that I need to declare the bindings inside the constructor which complicates things for me and I don't know how to refer to this attribute after that. For example, the following would not work... ``` constructor() { this.bindings = { myAttr : '@' }; } console.log(this.myAttr); ``` – luthien Mar 21 '18 at 15:25
  • Bindings have to be defined during component declaration because they need to be evaluated by the Angular parser. – H.B. Mar 21 '18 at 15:30
  • OK, indeed it makes sense. And then how would you refer to this? To print its value from the controller for example? – luthien Mar 21 '18 at 15:37
  • Just as you wrote by accessing `this.myAttr`. As mentioned in the answer you of course have to declare `myAttr` as a property of your class. Edited answer for clarity. (You may get an error if you use strict TS options.) – H.B. Mar 21 '18 at 15:41