angular在哪里存储任何输入元素的值



我来自jquery背景,试图学习angular,所以我创建了一个基本的表单组件,并设置表单元素的值。一切都按预期进行。我在设置和从表单元素获取值方面没有问题

我似乎不明白angular在哪里存储元素值?

when i executed this inside the console tab
document.getElementsByClassName('form-control')[0]                                                                                         

<input _ngcontent-ina-c83="" formcontrolname="fname" type="text" pinputtext="" 
class="form-control rounded ng-pristine ng-valid ng-touched" ng-reflect-name="fname">

Then when i executed this code
document.getElementsByClassName('form-control')[0].value

i got "John"   

问题:

  1. 我似乎不知道输入的值是如何存储的以及存储在哪里的,就像在jquery中一样,当我们设置值时,我们基本上可以在html中看到,它是在输入元素的value属性内部生成的。

  2. 此外,我很困惑,如果没有angular在html中设置的值属性beign,浏览器如何能够在输入框中正确显示值?我是不是错过了什么?

添加value属性并不是为输入元素设置值的唯一方法,它有助于在加载时设置默认值,但是JavaScript可以在不修改DOM的情况下设置值,这正是Angular所做的,JQuery在使用.val((更新输入字段的值时也会做类似的事情

document.querySelector("#change-val").addEventListener("click", () => {
let inputEl = document.querySelector("#sample-inp");
inputEl.value = "modified value";
//DOM will remain un-modified
console.log(inputEl.outerHTML);
});
<input id="sample-inp" type="text" value="default value"/>
<button id="change-val" type="button">change Value</button>

也就是说,Angular仍然在内部内存中维护绑定的formField的值,将它们映射到Observables,并在更改事件时更新它们。

您可以在angular中使用双向绑定。例如

在html代码中:

<input type="text" [(ngModel)]="userName" >

您应该在typescript中有一个名为"的变量;userName";。然后您可以在typescript中获取并设置userName。此外,如果您将";userName"在html页面中;userName"变量将在typescript中自动更新。。。

希望这能有所帮助!

Angular使用了一种名为双向绑定的东西,这使得访问值更加容易和高效。它使用ngModel指令允许您访问ts文件中的值。你可以在这里查看文档

但是,如果您想访问输入的值,这里有一个示例。您首先需要在ts文件中声明一个变量,然后将其绑定到ngModel:

ts

username: string;

HTML

<input [(ngModel)]="username"/>

通过这种方式,您可以读写您的输入值:

//Read Value
readValue(){
let inputValue = this.username;
}
//Set Value
setValue(){
this.username = "xyz";
}

相关内容

最新更新