You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何向组件函数传参并生成动态周天气预报

Angular: Pass Coords to Child Component's Method & Display Weekly Forecast

Got it, let's break this down step by step to get your weekly forecast working properly. Here's how to pass the coords to your child component's getForecast method and render the results:

1. Set Up Input Binding with Change Detection in Child Component

First, you need to receive the coords from the parent component and trigger getForecast whenever the coords value changes. The cleanest way to do this is using an @Input() setter (or you can use ngOnChanges if you prefer):

// weather.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'weather',
  templateUrl: './weather.component.html'
})
export class WeatherComponent {
  WeeklyForecast: any[] = []; // Adjust the type to match your actual forecast data structure

  // Use a setter to detect when coords change
  @Input() set coords(newCoords: string) {
    // Only call the method if coords are valid (avoid empty/undefined values)
    if (newCoords) {
      this.getForecast(newCoords);
    }
  }

  getForecast(coords: string): void {
    // Replace this with your actual API call or data processing logic
    // Example mock data to test rendering:
    this.WeeklyForecast = [
      { day: 'Monday', temp: '24°C', condition: 'Sunny' },
      { day: 'Tuesday', temp: '21°C', condition: 'Partly Cloudy' },
      { day: 'Wednesday', temp: '19°C', condition: 'Rainy' },
      // Add more forecast items as needed
    ];

    // If using an API, your code might look like this:
    // this.weatherApiService.getWeeklyForecast(coords).subscribe({
    //   next: (data) => this.WeeklyForecast = data,
    //   error: (err) => console.error('Failed to fetch forecast:', err)
    // });
  }
}

2. Update the Child Component Template to Render Forecasts

Now you can use *ngFor to loop through WeeklyForecast and display each item. Add a loading state to handle the gap before data is ready:

<!-- weather.component.html -->
<div *ngIf="WeeklyForecast.length === 0" class="loading">Loading weekly forecast...</div>

<ng-container *ngFor="let wfc of WeeklyForecast">
  <div class="forecast-card">
    <h3>{{ wfc.day }}</h3>
    <p class="temp">{{ wfc.temp }}</p>
    <p class="condition">{{ wfc.condition }}</p>
  </div>
</ng-container>

3. Parent Component Usage

Your parent component's template can stay mostly the same—just ensure you're passing the coords correctly to the child component:

<!-- parent.component.html -->
<weather [coords]="parentCoords"></weather>

Alternative: Using ngOnChanges Lifecycle Hook

If you prefer using the OnChanges hook instead of a setter, here's how that implementation would look:

// weather.component.ts
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'weather',
  templateUrl: './weather.component.html'
})
export class WeatherComponent implements OnChanges {
  @Input() coords!: string;
  WeeklyForecast: any[] = [];

  ngOnChanges(changes: SimpleChanges): void {
    // Check if coords changed and has a valid value
    if (changes['coords'] && changes['coords'].currentValue) {
      this.getForecast(changes['coords'].currentValue);
    }
  }

  getForecast(coords: string): void {
    // Same data processing/API call logic as before
  }
}

Key notes to keep in mind:

  • Always validate coords before calling getForecast to avoid unnecessary or invalid API calls.
  • For better type safety, create an interface (e.g., WeeklyForecastItem) that matches your forecast data structure instead of using any.
  • If using an API, don't forget to handle errors in your subscription to avoid uncaught issues.

内容的提问来源于stack exchange,提问作者Tommy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:57:38