I have components nested in the following hierarchy. Here are the relevant snippets of code:
+ HomeComponent:
- home.component.ts
initialText = '';
changeSearchText() {
this.initialText = 'text has been changed!';
}
- home.component.html
<app-search [searchText]="initialText"/>
+ SearchComponent [selector: app-search]
- search.component.ts
@Input() private searchText: string;
- search.component.html
<app-search-input [searchText]="searchText"/>
+ SearchInputComponent [selector: app-search-input]
- search-input.component.ts:
@Input() private searchText: string;
- search-input.component.html:
<input type="text" [value]="searchText">
So, in my HomeComponent I have a button with an event binding (click) to changeSearchText(). When I click the button in HomeComponent, changeSearchText() is fired. This changes the initialText value, due to property binding the change migrates down until the [value] binding in the nested SearchInputComponent is invoked and the field is updated.
However, this works ONLY the first time I click it. Subsequent clicks do fire changeSearchText() and the value of HomeComponent.initialText is changed but the change does not migrate down and the value in the input control is unchanged.
Why does it work the first time and not subsequent times? What am I missing here?
I tried to track using ngOnChanges and sure enough ngOnChanges on the child components is called the very first time but not subsequently.
Edit -- I discovered that this does not work even if you have a simple component with a text input field that is property bound with [value], works only the first time.
Thanks @R.Richards, that was it!! :) The 'text has been changed!' is the same value therefore it did not detect any change. I changed it to this and it changes every time without issues, good to know:
changeSearchText() {
const dateFmt = new Date().toLocaleString();
this.initialText = 'I changed the text! ' + dateFmt;
}