1

Html:

<map street="{{firstunit.street}}"/>

Component:

@Component('CustomerService', {
    templateUrl: '/CustomerService/_UnitCard/MapComponent/Map.html',
    selector: 'map',
    bindings: {
        street: '@',
    }
})
export class MapComponent {
    private x: string;


    public $onInit() {
        this.x = 'y';
    }

    public getValue() {
        console.log(this.x);
    }

}

I have a class that uses a $onInit to set a value. But I can't use that value in another function. When I call the function getValue() I log a 'undefined'. How can I set a value to the class property using a $onInit? (using angular 1.7 with typescript).

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185

1 Answers1

0

Don't use self-closing tags with components.

̶<̶m̶a̶p̶ ̶s̶t̶r̶e̶e̶t̶=̶"̶{̶{̶f̶i̶r̶s̶t̶u̶n̶i̶t̶.̶s̶t̶r̶e̶e̶t̶}̶}̶"̶ ̶/̶>̶
<map street="{{firstunit.street}}"></map>

See Are (non-void) self-closing tags valid in HTML5?

From the Docs:

Life-cycle hooks

Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the directive:

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

AngularJS Comprehensive Directive API Reference - Life-Cycle Hooks

The $onInit function should be provided as a method of the component controller. It is invoked by the $compile service after it binds the component attributes to the controller.

With components, the controller is bound to the $ctrl property of the component scope (or to the property specified by the controllerAs option).

If the getValue function is logging undefined, it is likely that it is doing so because it is being invoked before the $compile service invokes the $onInit function.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95