Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the analog of the 'controllerAs' directive's property in Angular 2 component?

I started to migrate one of my Angular 1 directives to the Angular 2 component.

The directive I am currently on has the controllerAs: 'ctrl' property and the directive's template uses 'ctrl.' prefix when it access properties.

Looking at the official ComponentMetadata doc I do not see any properties that can be used instead of this one.

like image 886
Dmitry Klochkov Avatar asked Jan 21 '16 16:01

Dmitry Klochkov


1 Answers

There is no equivalent to controllerAs in Angular 2. For example, given this controller class and template:

@Component({
    selector: 'component-a',
    template: `<div class="component-a">
                <div class="counter" (click)="increment()">Component A: {{counter}}</div>
              </div>`
})
export class ComponentA {

    counter = 0;

    increment() {
        this.counter += 1;
    }

}

In the method increment(), this is bounded to the controller instance of that particular component itself. In the template, the counter can be accessed via {{counter}}.

As we can see there is no mechanism to name the controller because we can already access it using the default functionality.

You can either think that the controllerAs mechanism has been integrated in the default component functionality of Angular 2, or that functionality has been removed as its no longer needed, depending on how you look at it.

like image 119
Angular University Avatar answered Oct 16 '22 08:10

Angular University