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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38358306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:34:31  来源:igfitidea点击:

Angular - Setting value in input text box in another component

htmlangulartypescripttextbox

提问by Jeet Prakash

I am trying to set the value in an HTML input text box which is a part of ComponentAfrom the typescript code which is a part of ComponentB.

我正在尝试在 HTML 输入文本框中设置值,该文本框中是ComponentA打字稿代码的一部分,它是ComponentB.

Taking a clue from thisSO 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 中

采纳答案by Jeet Prakash

This is one of the cases when user interaction on one component ComponentAtriggers an update on another component ComponentB.

这是当用户在一个组件上的交互ComponentA触发另一个组件上的更新时的一种情况ComponentB

This articledescribes 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.

有关更多方法,请访问另一个链接

回答by Pardeep Jain

If you are trying to set the value of component1's textfield from the compoenent2 then you must have to use of ngModeli.e two way data binding. 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. like this

如果您试图从组件 2 设置组件 1 的文本字段的值,那么您必须使用ngModelie 双向数据绑定。通过在提供者列表中提供 component2,您可以访问该组件的所有函数和变量,然后您可以轻松设置您的值。像这样

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

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**