我正在构建天气应用程序,我使用角度5作为我的前端框架和本地存储作为我的存储。 我将城市名称从输入字段保存到本地存储。这里的主要问题是,当我保存城市名称时,我想要更改我的视图,即我想隐藏输入字段并显示我之前保存的城市名称。 我的下一个功能是从本地存储中删除城市名称。在这种情况下,我也想改变我的观点,即我想隐藏城市名称和显示输入字段。这是我的代码
settings.component.html
<div class="row">
<div class="col-md-6 col-xl-8 mt-4 col-center">
<div class="card">
<div class="card-body">
<h3 class="text-center pt-2 pb-2">Setttings</h3>
<hr>
<div class="setting-menu">
<span class="setting-items">
<h5>Add Your City</h5>
</span>
<div *ngIf="storedCity" class="localstorage" #cityDiv>
<div class="storedCity">
<span> {{storedCity | uppercase}} </span>
</div>
<div class="remove-city mt-4">
<span class="remove-icon ml-5">
<i class="fa fa-times" aria-hidden="true" (click)="removeCity()" ></i>
</span>
</div>
</div>
<div class="clearfix"></div>
<div *ngIf="!storedCity" class="city-input pt-4" #inputDiv>
<form action="">
<div class="form-group">
<input type="text" [(ngModel)]="cityName" name="cityName" value={{cityName}} id="cityName" class="form-control" placeholder="Add City ......">
</div>
<div class="form-group">
<button class="btn btn-success add-btn" (click)="update()">Add</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
settings.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-settings',
templateUrl: './settings.component.html',
styleUrls: ['./settings.component.scss']
})
export class SettingsComponent implements OnInit {
@ViewChild('cityDiv') cityDiv;
@ViewChild('inputDiv') inputDiv;
public cityName: string;
public storedCity = localStorage.getItem("City");
constructor() {
this.cityName = '';
}
ngOnInit() {
}
update() {
localStorage.setItem("City", this.cityName);
this.cityName = '';
}
removeCity() {
localStorage.removeItem("City");
}
}
答案 0 :(得分:1)
在设置值
时将* ngIf添加到输入中<input *ngIf='!cityName; else citySet' type="text" [(ngModel)]="cityName" name="cityName" value={{cityName}} id="cityName" class="form-control" placeholder="Add City ......">
然后只显示值
<ng-template #citySet>{{cityName}}</ng-template>