Friday, September 29, 2017

A more object oriented Angular 1.5+ component

I can’t use Angular 2 where I am, but I like how it’s more object oriented (components are classes). We are starting to use Angular 1.5+ components and to eventually ease transition I was looking at using the new javascript functionality of classes to make components classes with Angular 1.5+. Partially just messing around here as well to see what I can come up with.

The specific question I have is that when I define $onInit by setting it to a class function it doesn’t get called but when I define it as an anonymous function it does and I’m not 100% sure why. Any help would be great. A generic question would be does anyone have ideas around how to do this simulation of app.component() to javascript class?

class Component {
    constructor(name, templateUrl, bindings, controllerAs) {
        app.component(name, {
            templateUrl: templateUrl,
            bindings: bindings,
            controllerAs: controllerAs,
            controller: this.controller
        });
    }

    controller() {
        console.log("Inside Component controller");
    }
}

class ListNames extends Component {
    constructor() {
        super("listNames", "ListNames.html", { names: '<' }, "lstNames");
    }

    onInit() {
        console.log("onInit called");
    }

    // overrided method
    controller() {
        console.log("ListNames controller()");
        /*this.$onInit = function () {
            console.log("onInit called");
        }*/
        this.$onInit = this.onInit; // <-- this doesn't work but the above does
    }
}

lstNames = new ListNames();

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/a-more-object-oriented-angular-1-5-component/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment