Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 885
Jeet Prakash Avatar asked Jul 13 '16 17:07

Jeet Prakash


People also ask

How to bind input value in Angular?

You can use Angular event bindings to respond to any DOM event. Many DOM events are triggered by user input. Binding to these events provides a way to get input from the user. To bind to a DOM event, surround the DOM event name in parentheses and assign a quoted template statement to it.

How do I change input values in TypeScript?

To get the value of an input element in TypeScript: Select the input element. Type the input element as HTMLInputElement using a type assertion. Use the value property to get the element's value.

How to give input in Angular?

The first step to passing data into an Angular component is to create a custom property to bind to. This is done via “input” binding to pass data from one component to another (typically parent to child). This custom input binding is created via the @Input() decorator!

What is TextBox in Angular?

The Angular TextBox (text field) is a component for editing, displaying, or entering plain text on forms to capture user names, phone numbers, email, and more.


1 Answers

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

like image 187
Pardeep Jain Avatar answered Oct 07 '22 22:10

Pardeep Jain