Recently, I delved into Angular because I anticipate needing to use it down the line.
My current focus is on studying components communication, particularly from child to parent. I came across various methods of achieving this. In each example, the ChildComponent has the following property:
@Output changeSignal : EventEmitter = new EventEmitter<string>();
First approach
<input [(ngModel)]='message' (keyup)='handleKeyUp' />
message : string : '';
handleKeyUp() : void {
this.changeSignal.emit(this.message);
}
Using this solution involves having a property solely for transmitting data to the parent, which I find inefficient as it stores unnecessary data.
Second approach
<input (keyup)='handleKeyUp($event)' />
handleKeyUp(event : any) : void {
this.changeSignal.emit(event.target.value);
// console.log(event.constructor.name);
}
In this method, the event type is not specified, a practice that I do not deem favorable in typescript.
Third approach
The console.log() output from the previous approach indicates KeyboardEvent and event.target is of type EventTarget. However, this class does not seem to define the 'value' property.
handleKeyUp(event : KeyboardEvent) : void {
// Error in the terminal
this.changeSignal.emit(event.target.value);
}
The 'value' property is specific to certain HTMLElements, like HTMLInputElement. To avoid errors, you must cast it:
handleKeyUp(event : KeyboardEvent) : void {
this.changeSignal.emit((<HTMLInputElement>event.target).value);
}
This does not seem ideal.
Fourth approach
<input (keyup)='handleKeyUp($event.target.value) />
HandleKeyUp(inputContent : string) : void {
this.changeSignal.emit(inputContent);
}
In this approach, the input tag manages its specific behavior, but it complicates the readability of the HTML template and includes behavior that should be in the JavaScript file.
Which of these four approaches do you consider best practice?