1. Implementing Conditional Display with *ngIf in Angular
If you are facing issues with displaying intermediate values for city in your child component while the user is typing a city name in the parent component, and you only want to show the final city name in the child component after the user clicks on 'getWeather' button to fetch weather data, you can solve this by using a conditional check with *ngIf in your child template.
This way, the city will only be displayed in the child component when the weather data is available, eliminating the display of intermediate values for 'testCity'.
Child Component Template:
<p *ngIf="weather">{{ testCity }}</p>
<div>{{ weather }}</div>
@Input() testCity: string;
@Input() weather: string;
Parent Component Template:
<input matInput type="text" [(ngModel)]="city">
<button mat-button (click)="getWeather()">Get Weather</button>
<app-city-weather [testCity]="city" [weather]="weather"></app-city-weather>
city: string;
weather: string;
getWeather() {
this.weather = 'Sunny';
}
2. Using Subject to Send Data from Parent to Child as an Event
If you need to send data as an event from the parent to the child component, you can utilize a Subject in the parent component and pass it as an Observable to the child, where you can subscribe to value changes.
Child Component Template:
<p>{{ city$ | async }}</p>
@Input() city$: Observable<string>;
Parent Component Template:
If you only require the city value in the getWeather function and the child component, you can remove [(ngModel)="city"] and directly access the input value to pass to getWeather.
<input #cityInput matInput type="text">
<button mat-button (click)="getWeather(cityInput.value)">Get Weather</button>
<app-city-weather [city]="currentCity.asObservable()"></app-city-weather>
currentCity: Subject<string> = new Subject<string>();
getWeather(city: string) {
// Send current city to child
this.currentCity.next(city);
}