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

為{幸葍}努か 提交于 2020-01-03 15:16:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/34928467/what-is-the-analog-of-the-controlleras-directives-property-in-angular-2-compo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!