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
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.
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.
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!
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.
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**
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With