Angular 5根据Array函数动态更改图像ngFor

时间:2018-04-26 16:50:07

标签: angular typescript angular5

我正在尝试使用ngFor

获取动态更改HTML的图像

所以我做的是:

循环遍历数组并根据当前天气更改变量的值:

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { WeatherService } from '../weather.service';
import { forEach } from '@angular/router/src/utils/collection';


@Component({
  selector: 'app-weather-component',
  templateUrl: './weather.component.html',
  styleUrls: ['./weather.component.css']
})
export class WeatherComponent implements OnInit {

  weatherImg: string;
  clouds: string;
  sun: string;

  public shown = false;
  cityName: string;
  weathers: any = [];
  forecasts: any = [];
  weatherType: string;
  forecastType: string;
  forecastImg: string;

  constructor(private _weatherService: WeatherService) {


  }

  ngOnInit() {
    setInterval(this.submitDataBox.bind(this, this.cityName), 60000);
    setInterval(this.submitData.bind(this, this.cityName), 60000);
    setInterval(this.weatherImage.bind(this), 10000);
  }

weatherImage() {

 // const weatherType = this.weathers.weather[0].main;

for (let i = 0, len = this.forecasts.list.length; i < len; i++) {

        if ( this.forecasts.list[i].weather[0].main.toLowerCase().indexOf('rain') > -1 ) {

        this.forecastImg = 'http://icons.iconarchive.com/icons/icons8/ios7/96/Weather-Rain-icon.png';

        console.log(this.forecasts.list[i].weather[0].main);

} else if (this.forecasts.list[i].weather[0].main.toLowerCase().indexOf('clouds') > -1) {
  this.forecastImg = 'http://icons.iconarchive.com/icons/icons8/windows-8/96/Weather-Clouds-icon.png';

}
}

在component.html中:

           

五天详细预测             

      <div class="col-md-3 col-sm-6 mb-4">
        <a href="#">
          <img class="img-fluid" bind-src="forecastImg">
        </a>
        <h5>Date: {{forecast.dt_txt | date : 'short' }}</h5>
            <p > {{ forecast.weather[0].main }}</p>
            <p > {{ forecast.weather[0].description }}</p>
            <p > {{ forecast.weather[0].icon }}</p>
            Temperature <p >{{ forecast.main.temp }}</p>
      </div>



    </div>
    </div>
    <!-- /.row -->

但不幸的是,结果是我只获得了所有项目的第一张图片(http://icons.iconarchive.com/icons/icons8/ios7/96/Weather-Rain-icon.png

而不是根据输出放置图像

4 个答案:

答案 0 :(得分:1)

您只创建一个forecastImg变量,而不是在每个预测实例上创建一个变量。

我已经汇总了一个工作示例,我在每个预测中创建了一个新的image属性。

https://stackblitz.com/edit/angular-gsbrv9

答案 1 :(得分:0)

你关闭了你的标签吗?

<div *ngFor=" let forecast of forecasts.list">
  <div class="col-md-3 col-sm-6 mb-4">
    <a href="#">
      <img class="img-fluid" bind-src="forecastImg">
    </a>
  <div>
<div>

答案 2 :(得分:0)

问题是您要设置this.forecastImg,其中this是组件,而不是forecast。在你的循环中,你只需覆盖图像(实际上,你应该得到所有项目的最后一个图像,而不是第一个图像)

您需要做的是创建图像/预测列表,而不仅仅是单个图像。我假设this.forecasts是来自某个http调用的结果,所以让我们在控制器的顶部创建一个新变量(而不是forecastImg)。我还建议使用一个对象来查找图标而不是if / else:

// ideally you create an interface for a forecast
forecastItems: any[] = [];

// create an object for the icons that you can use for lookups
icons = {
  'rain': 'http://icons.iconarchive.com/icons/icons8/ios7/96/Weather-Rain-icon.png',
  'clouds': 'http://icons.iconarchive.com/icons/icons8/windows-8/96/Weather-Clouds-icon.png'
}

我将使用ES6循环预测并将图像分配给我们的数组

for (let item of this.forecasts.list) {
  // here we could use that interface again
  const forecastItem = {
    'title': item.weather[0].main,
    'icon': ''
  }
  // assign the icon if we have one
  try {
    forecastItem['icon'] = this.icons[forecastItem.title.toLowerCase()];
  } catch (e) {}

  // store the object in our helper array
  this.forecastItems.push(forecastItem);
}

现在,您有一系列带有标题和图标的预测,您可以在模板中使用这些预测:

<div *ngFor="let forecast of forecastItems">
  <div class="col-md-3 col-sm-6 mb-4">
    <a href="#">
      <img class="img-fluid" bind-src="forecast.icon" alt="{{ forecast.title }}">
    </a>
  <div>
<div>

答案 3 :(得分:0)

只是一个建议,而不是图像的单个变量,你可以这样做:

EXEC sp_execute_external_script  @language =N'Python',
@script=N'
import pandas as pd
s = pd.Series([5,6,7,8,9,10])
df = pd.DataFrame(s)
df.reset_index(inplace=True)
OutputDataSet = df
'
WITH RESULT SETS (( MyIndex int, test int ));

然后在你的模板中:

this.forecasts.list.forEach((forecast) => { 
if (forecast.weather[0].main.toLowerCase().indexOf('rain') > -1 ) { 
forecast['forecastImg'] = 'http://icons.iconarchive.com/icons/icons8/ios7/96/Weather-Rain-icon.png';
} else if (forecast.weather[0].main.toLowerCase().indexOf('clouds') > -1) { 
forecast['forecastImg'] = 'http://icons.iconarchive.com/icons/icons8/windows-8/96/Weather-Clouds-icon.png'; } });