Search code examples
htmlangulartypescripttextbox

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.

Taking a clue from this SO i tried doing:

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


Solution

  • This is one of the cases when user interaction on one component ComponentA triggers an update on another component 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.

    For more approaches here is another link.