14

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

Jeet Prakash
  • 625
  • 1
  • 7
  • 13

2 Answers2

20

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

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • @pradeep, thanks for the plunker for `ngModel` example, though i would not want the value to be assigned at the same place it is declared, rather i would want to update the input box via `ngModel` via a function call. So i changed the declaration to be `name:string;` and in the `DeleteFunction()` function i put `name = "pradeep";` Is it supposed to work? Sorry for acting like a newbie, it is my first stab at Angular2 – Jeet Prakash Jul 14 '16 at 06:50
2

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.

Jeet Prakash
  • 625
  • 1
  • 7
  • 13