Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Could add easy @ViewChild in Typescript/ES6 #169

Open
artem-v-shamsutdinov opened this issue Jun 17, 2016 · 0 comments
Open

Could add easy @ViewChild in Typescript/ES6 #169

artem-v-shamsutdinov opened this issue Jun 17, 2016 · 0 comments

Comments

@artem-v-shamsutdinov
Copy link

artem-v-shamsutdinov commented Jun 17, 2016

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 :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant