Issue
Here is a simple component that receives an inputValue
and binds it to an input field:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-custom-input',
template: `
<input [(ngModel)]="inputValue">
`,
})
export class CustomInputComponent {
@Input() inputValue: string;
}
I'm curious if its fine to do so, or maybe it's better to do it this way with localInputValue
:
@Component({
selector: 'app-custom-input',
template: `
<input [(ngModel)]="localInputValue">
`,
})
export class CustomInputComponent {
@Input() inputValue: string;
localInputValue:string;
ngOnInit(){
this.localInputValue = this.inputValue
}
}
I understand that in the first case, if Input changes, it would set value of the input field to that value, and that might erase user's input. However, if the Input doesn't change is there any convention regarding if the first or second way should be used/prefered?
Solution
The problem with this approach it's that the change of the input not change the variable in the "parent", and a change of the variable in parent not change the value in child
You can use setters
export class CustomInputComponent {
get localInputValue(){
return this.inputValue
}
set localInputValue(value:string)
{
this.inputValue=value;
this.inputValueChange.emit(value)
}
@Input() inputValue: string;
@Output() inputValueChange:eventEmitter<string>=new eventEmitter<string>()
Well, if you needn't two-way-binding, you can use Input, in this way, when change in parent, change in child.
export class CustomInputComponent {
localInputValue:string="";
@Input('inputValue') set _(value:string){
this.localInputValue=value;
}
You can see in action in this stackblitz. See that in child2 when change in child2, not change in parent, but when you change from parent change in child
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.