简体   繁体   English

Angular - 在另一个组件的输入文本框中设置值

[英]Angular - Setting value in input text box in another component

I am trying to set the value in an HTML input text box which is a part of ComponentA from the typescript code which is a part of ComponentB . 我试图在HTML输入文本框中设置值,该文本框是作为ComponentA一部分的打字稿代码的ComponentB的一部分。

Taking a clue from this SO i tried doing: 这个 SO中获取线索我尝试做:

(<HTMLInputElement>document.getElementById("name")).value = response.name;

But this is not working. 但这不起作用。 Is there anything else i need to take care of? 还有什么我需要照顾的吗?

EDIT: The element with Id "name" is in ComponentA and the above code that is trying to manipulate that element is in ComponentB 编辑:具有Id "name"的元素在ComponentA中,上面的代码试图操纵该元素在ComponentB中

If you are trying to set the value of component1's textfield from the compoenent2 then you must have to use of ngModel ie two way data binding. 如果您尝试从ngModel设置component1的文本字段的值,则必须使用ngModel即双向数据绑定。 by providing component2 in the providers list you are able to access all the functions and variables of that component, then you can easily set your value. 通过在提供者列表中提供component2,您可以访问该组件的所有功能和变量,然后您可以轻松设置您的值。 like this 像这样

suppose this is your component 2's value property 假设这是你的组件2的value属性

name:string = 'Pardeep Jain';

than you can access this in component like this- 你可以在这样的组件中访问它 -

<input type="text" [(ngModel)]='name'>
....
constructor(private delete1: Delete){
   this.name = this.delete1.name;
}

Working Example 工作实例

Also

(<HTMLInputElement>document.getElementById("name")).value = response.name;

is used to set the value of current template's field with id named as **name** 用于设置当前模板的字段的值,其id named as **name**

This is one of the cases when user interaction on one component ComponentA triggers an update on another component ComponentB . 这是一个组件ComponentA上的用户交互触发另一个组件ComponentB上的更新的情况之一。

This article describes multiple approaches, with example code, on how to pass information between components. 本文介绍了有关如何在组件之间传递信息的多种方法,以及示例代码。

My personal favorite is the third approach mentioned in that article in which one of the component (say ComponentA ) "listen" for update it is concerned about from any component (say ComponentB ) via a service in between them, resulting in a loosely coupled components. 我个人最喜欢的是该文章中提到的第三种方法,其中一个组件(比如ComponentA )“监听”更新,它通过它们之间的服务从任何组件(比如ComponentB )关注,导致组件松散耦合。

For more approaches here is another link . 对于更多方法,这里是另一个链接

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

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