Jeet Prakash
Jeet Prakash

Reputation: 643

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

Upvotes: 15

Views: 92713

Answers (2)

Jeet Prakash
Jeet Prakash

Reputation: 643

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.

Upvotes: 2

Pardeep Jain
Pardeep Jain

Reputation: 86720

If you are trying to set the value of component1's textfield from the compoenent2 then you must have to use of ngModel i.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

suppose this is your component 2's value property

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

Upvotes: 21

Related Questions