带有"this"的数据插值绑定行为.关键字,且不含"this";关键字的角度? [英] Data interpolation binding behavior with "this" keyword and without "this" keyword in angular?

查看:86
本文介绍了带有"this"的数据插值绑定行为.关键字,且不含"this";关键字的角度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码是我的组成部分

Below code is my component

@Component({
    selector: 'my-app',
    template: '<div>{{name}}</div>'
})

export class MyApp {
    name: String = '';
    constructor(){
        this.name = 'Mr_Perfect';
    }

}

在模板中,我知道提到{{name}}时数据将绑定.但是,如果我将其更改为{{this.name}},它也可以正常工作.

In the template I know that the data will bind when I mention {{name}}. But it is also working if I change it to {{this.name}}.

有什么区别吗?哪个更好用?

Is there any difference? Which is better one to use?

推荐答案

从Angular 2 RC5开始,似乎他们在模板中启用了this的使用.我尝试使用Angular 2 BetaAngular 2 FinalAngular 4进行此操作,并且在后两者中均有效.

It seems like they enabled the use of this in the template since Angular 2 RC5. I tried this with Angular 2 Beta, Angular 2 Final and Angular 4 and it works in the latter two.

以下是一些在线示例(默认情况下未添加this,请在模板中添加)

Here are some live examples (this has not been added by default, do it so in the template)

使用Angular 2 Beta的柱塞示例<-不起作用
使用Angular 2 Final的柱塞示例<-工作中
使用Angular 4的柱塞示例<-工作

Plunker Example using Angular 2 Beta <- Not Working
Plunker Example using Angular 2 Final <- Working
Plunker Example using Angular 4 <- Working

角度模板可以访问Component Class局部的所有变量.这意味着与必须在其中放置this来访问类中的变量的函数内部不同,在模板中不需要这样做,但是在2.x和4.x中,可以根据需要这样做./p>

The angular template can access all variables local to the Component Class. This means unlike within functions where you must put this to access the variables in the class, you aren't required to do so in the template but in 2.x and 4.x, you can do so if you want.

@Component({
    selector: 'my-app',
    template: `<div>{{name}}</div>       <!-- Angular 2 & Angular 4 -->
               <div>{{this.name}}</div>  <!-- Angular 4 Only -->`
})

export class MyApp {
    name: string = '';
    constructor(){
        this.name = 'Mr_Perfect';
      // ^ required
    }

    get(name: string)
    {
        return this.name;
             // ^ required
    }

}

这篇关于带有"this"的数据插值绑定行为.关键字,且不含"this";关键字的角度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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