import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CommonService {
public defaultCity:string = "武汉"
constructor() { }
getCity(){
if(localStorage.getItem("city")){
this.defaultCity =localStorage.getItem("city")
}
return this.defaultCity;
}
changeCity(value:string){
this.defaultCity = value;
localStorage.setItem("city",value)
}
}
import { Component, OnInit } from '@angular/core';
import {CommonService} from '../../services/common.service'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
public hotCities:string [] =["北京","上海","深圳","武汉","杭州"]
public city:any
constructor(public common:CommonService) { }
ngOnInit() {
this.city = this.common.getCity()
}
handlecilck(city:string){
console.log(city)
this.common.changeCity(city)
}
}
使用
<p>{{common.defaultCity}}</p>
<h2>热门城市</h2>
<button *ngFor="let item of hotCities" class="bin"
(click)="handlecilck(item)">{{item}}</button>