账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于Angular中template variable reference的疑惑
    44
    0

    大家好,有个奇怪的疑惑如下例:

    <input #pin1 type="password">
    <p>You entered: {{pin1.value}}</p>
    

    如果在输入框任意输入,下方<p>中内容无变化,说明pin1.value没有值,间接说明#pin1这个variable reference没起到作用?

    另一方面我们加一个event binding,立刻有效

    <input #pin2 type="password" (input)="test(pin2)">
    <p>You entered: {{pin2.value}}</p>
    where test=function(x){console.log(x);}

    这次输入框任意输入,下方<p>中内容相应变化,证明#pin2这个variable reference开始工作,事实上event handler可以是任意函数,例如:

    <input #pin3 type="password" (input)="test()">
    <p>You entered: {{pin3.value}}</p>
    where test=function(){}

    也就是说只要且必须有event binding,variable reference才能起作用,请问这是为什么,另一个测试是:

    <input #pin4 type="password" (blur)="test()">
    <p>You entered: {{pin4.value}}</p>
    where test=function(){}

    任意输入无效,输入框失去焦点后立刻有效,所以我推断和event binding有关,与event种类和event handler具体实现无关,但是如何正确解释这个问题?我查看了官方doc也在stack overflow上提问了,可是无人回答= =,希望各位朋友帮忙,非常感谢!

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 云上城桥 普通会员 1楼

      在Angular中,模板变量引用(Template reference)是指在模板中使用变量引用的方式。这可以在指令(指令的HTML部分)和服务中实现。

      模板变量引用的使用方法如下:

      1. 指令使用变量引用:

      在指令中,您可以使用{{ variable }}来引用模板中的变量。例如:

      ```html

      {{ greeting }}

      ```

      这将返回模板中greeting的值。

      1. 服务使用变量引用:

      服务可以使用$http等API来获取数据并将其绑定到模板中的变量中。例如:

      ```typescript import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http';

      @Injectable({ providedIn: 'root' }) export class greetService { constructor(private http: HttpClient) {}

      greet() { return this.http.get('https://jsonplaceholder.typicode.com/todos/1') .subscribe( data => { console.log(data); }, error => console.error(error) ); } } ```

      在这个例子中,我们定义了一个服务greetService,它使用$http服务获取一个数据。然后,我们在模板中使用{{ greeting }}来引用这个变量。

      总的来说,模板变量引用在Angular中是非常有用的,因为它使得您可以使用变量在指令和服务中引用模板,从而提高代码的可维护性和可重用性。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部