ngUpgraders / ng-forward

The default solution for those that want to write Angular 2.x style code in Angular 1.x
410 stars 36 forks source link

Could add easy @ViewChild in Typescript/ES6 #169

Open artem-v-shamsutdinov opened 8 years ago

artem-v-shamsutdinov commented 8 years ago

Guys, not sure if you'll be interested but I just implemented this for ourselves cause we really needed it:

` export function ViewChild( // childComponentConstructor:Function, // childComponentAs:string = '$ctrl' // ) {

    function findChildComponent(currentScope:any):any {
        while (currentScope) {
            let currentComponent = currentScope[childComponentAs];
            if (currentComponent
                && currentComponent.constructor === childComponentConstructor) {
                return currentComponent;
            }
            currentComponent = findChildComponent(currentScope.$$nextSibling);
            if (currentComponent) {
                return currentComponent;
            }
            currentScope = currentScope.$$childHead;
        }
        return null;
    }

    return function (target, propertyKey:string) {
        Object.defineProperty(target, propertyKey, {
            get: function () {
                if(!this.$scope) {
                    throw `'private $scope' must be set on a component using @ViewChild decorator`;
                }
                return findChildComponent(this.$scope.$$childHead);
            },
            set: function (val) {
                throw `Cannot override child component reference for ${propertyKey}}`;
            }
        });
    }

}

`

It can be used this way in a 1.5 Component:

@ViewChild(ChildComponent) test:ChildComponent;

Of course it is only usable once the child component is initialized.

Anyway it would be great if you could add something like this :)