简体   繁体   English

Angular 模板变量引用

[英]Angular template variable reference

Here is a weird problem in Angular:这是 Angular 中的一个奇怪的问题:

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

If you type something in <input> , the <p> 's content will not change which means pin1.value does not have value, does it mean the variable reference #pin1 does not work?如果您在<input><input><p>的内容不会改变,这意味着pin1.value没有值,这是否意味着变量引用#pin1不起作用?

On the other hand, if we add a function to pass the reference, it will work.另一方面,如果我们添加一个函数来传递引用,它将起作用。

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

where test=function(x){console.log(x);}其中test=function(x){console.log(x);}

For this <input> , if we type something, the the <p> 's content will change to corresponding text which implies #pin2 works.对于这个<input> ,如果我们输入一些东西, <p>的内容将更改为相应的文本,这意味着#pin2有效。

So, the question is, in Angular, why we must use function to pass variable reference firstly then we can use it, why we cannot directly use variable reference.所以,问题是,在 Angular 中,为什么我们必须先使用函数来传递变量引用,然后才能使用它,为什么不能直接使用变量引用。

Firstly, that is not how binding works.首先,这不是绑定的工作方式。 What you did is creating a reference to input Dom object.您所做的是创建对输入 Dom 对象的引用。 At the time of the creation, the value of that Dom element (input) was empty.在创建时,该 Dom 元素(输入)的值为空。 hence no value showing in your <p> tag.因此,您的<p>标签中没有显示任何值。 if you want to see the value as you type then you are looking for a 2 way binding like so如果您想在键入时查看值,那么您正在寻找像这样的 2 路绑定

<input [(ngModel)]="pin" type="password">
<p>You entered: {{pin}}</p>

Assuming that pin is declared in your ts file.假设 pin 在您的 ts 文件中声明。

As to why the value was updating when you introduces a function, the answer is because Angular will be calling that function test(pin2) whenever you type something into that input which results in running a detect change on the model.至于为什么当您引入一个函数时该值会更新,答案是因为每当您在该输入中键入内容时,Angular 都会调用该函数 test(pin2),这会导致在模型上运行检测更改。

Long story short, Angular is a Model driven framework, if you need a value, you shouldn't need to get the DOM element to get the value from there.长话短说,Angular 是一个模型驱动的框架,如果你需要一个值,你不应该需要获取 DOM 元素来从那里获取值。

我可能会得到一个模棱两可的答案,它可能与事件绑定有关,即“view-to-source”,如果我们没有绑定任何事件,则视图(用户交互)无法将数据传递给源(组件类) ,因此变量引用可能不起作用,但仍然存在一些问题,例如模板引用不应与源端相关,因为此类变量不是组件类的成员/属性。

it is so werired behaviour in angular this code not working angular 这个代码不起作用

<input #inputval type="text"  />
<app-newcomp [testValue]="inputva.value"></app-newcomp>

but if you add "input" event to the input element then it will work但是如果你向输入元素添加“输入”事件,那么它就会起作用

<input #inputval type="text" (input)="someFunctionInTs($event)"  />
<app-newcomp [testValue]="inputva.value"></app-newcomp>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM