In my Angular project, I created a search box with a button to get a search result from another component. I have a router outlet in my App Component and I switch router outlet with the search result component using the search value variable. I use a service to share this search value variable between components. So, when I click on a link in html, the router outlet will appear. When I click on the search input and do a search, search result will appear. My problem is, when the router outlet is activated, I have to click twice on search button or hit twice enter key to appear the search result.
Code -
search.component.ts:
export class SearchComponent implements OnInit {
value: string;
constructor(private data: SendDataService){}
show: boolean = true;
showEl(){
this.show = true;
}
newValue() {
this.data.changeValue(this.value)
this.show = false;
}
ngOnInit(): void{
this.data.currentValue.subscribe(value => this.value = value)
}
}
search.component.html:
<input type="text" [(ngModel)]="value" (click)="showEl()" (keyup.enter)="newValue()" (input)="showEl()">
<button (click)="newValue()">Search</button>
search-result.component.ts:
export class SearchResultComponent implements OnInit {
_postsArray: = //JSON Object;
value: string = "";
filterarray: any[] = [];
constructor(private data: SendDataService){}
getData(){
this.data.currentValue.subscribe(value => {this.value = value;
this.showData();
})
}
showData(){
if (this.value != null){
this.filterarray=
this._postsArray.filter(f =>
f.title.toLowerCase()
.includes(this.value.toLowerCase()))
.map(searchname=>searchname.title)
}
}
ngOnInit(): void{
this.getData();
}
}
app.component.html:
<div>
<div *ngIf="!value">
<router-outlet></router-outlet>
</div>
<div *ngIf="value">
<app-search-result></app-search-result>
</div>
</div>
When I put {{value}} in app.component.html, it shows the value at the first click of search button. but <app-search-result>
only appears in second click. How can I solve this?