I have a child textbox component as "app-ec-textbox"
HTML for app-ec-textbox
<input type="text" #txtBox [ngModel]="value" (focus)="validate(value)">
in ts file for app-ec-textbox, I have function validate() defined as below
@Input() value: string = "";
validate(val: string) {
console.log(val)
}
i use above child textbox component in parent component like below
<app-ec-textbox [value]="abc"></app-ec-textbox>
The problem is I don't get value "abc" logged in console when I click and set focus on child textbox component "app-ec-textbox". I want value "abc" to be captured in focus event. How to achieve this?
CodePudding user response:
You have to change it to a focus event (focus)="validate($event)"
<input type="text" #txtBox [(ngModel)]="value" (focus)="validate($event)">
validate(event: any) {
console.log(event.target.value)
}
CodePudding user response:
When you pass values to properties declared in []
you're passing directly code, just to be clear, i'll make an example:
This:
<app-ec-textbox [value]="abc"></app-ec-textbox>
It's equal to this:
<app-ec-textbox value="{{ abc }}"></app-ec-textbox>
In this way you're evaluating some code before and then your passing the returned value to the prop.
You haven't posted anything related to some prop called abc
so what's appening is that angular tries to find a variable called abc
and pass its value to the child prop.
If you want to pass just a string of course yo ucan do that by:
<app-ec-textbox [value]="'abc'"></app-ec-textbox> <!-- note the ' -->
But you can just:
<app-ec-textbox value="abc"></app-ec-textbox>
Now that you're passing the right values to the child you have to bind the property with the ng model, to do that you can use the two-way binding to the value:
<input type="text" #txtBox [(ngModel)]="value" (focus)="validate(value)">