Exploring how to achieve two-way binding in Angular 2, I am currently working with the following parent component setup:
app.component.html:
<child [(text)]="childText" (textChanged)="textChanged($event)"></child>
<span>{{childText}}</span>
app.components.ts:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
childText = 'Initial text value';
textChanged(newValue: string) {
console.log(this.childText); // This always logs "Initial text value"
console.log(newValue); // Outputs the new value from the child component input
}
}
child.component.html:
<input #inputEl [value]="text" (keyup)="text = inputEl.value">
child.component.ts:
@Component({
selector: 'child',
templateUrl: 'child.component.html',
styleUrls: ['child.component.scss']
})
export class ChildComponent {
private _text: string;
@Output() textChanged: EventEmitter<string> = new EventEmitter<string>();
@Input()
get text(): string {
return this._text;
}
set text(value) {
this._text = value;
this.textChanged.emit(value);
}
constructor() { }
}
Upon changing the text within the input
element of the child
component, the {{childText}} displayed in the app
component template reflects the new value, while this.childText
retains its initial value.
I wondered if there was a way to update this.childText
without relying on a callback from the child
component. Additionally, why does
<span>{{childText}}</span>
only reflect the updated value?