Angular 2 组件中“controllerAs"指令的属性的模拟是什么? [英] What is the analog of the 'controllerAs' directive's property in Angular 2 component?

查看:24
本文介绍了Angular 2 组件中“controllerAs"指令的属性的模拟是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始将我的 Angular 1 指令之一迁移到 Angular 2 组件.

我当前使用的指令具有 controllerAs: 'ctrl' 属性,并且该指令的模板在访问属性时使用 'ctrl.' 前缀.

查看 官方 ComponentMetadata 文档看不到任何可以用来代替这个属性的属性.

解决方案

Angular 2 中没有与 controllerAs 等效的方案.例如,给定这个控制器类和模板:

@Component({选择器:'组件-a',模板:`<div class="component-a"><div class="counter" (click)="increment()">组件A:{{counter}}</div>

`})导出类 ComponentA {计数器 = 0;增量() {this.counter += 1;}}

在方法 increment() 中,this 绑定到该特定组件本身的控制器实例.在模板中,可以通过 {{counter}} 访问计数器.

正如我们所见,没有命名控制器的机制,因为我们已经可以使用默认功能访问它.

您可以认为 controllerAs 机制已集成到 Angular 2 的默认组件功能中,或者该功能已被删除,因为不再需要它,这取决于您如何看待它.

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.

解决方案

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.

这篇关于Angular 2 组件中“controllerAs"指令的属性的模拟是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆