javascript - 角; 当我在脚本中更新变量时如何重新渲染组件数据。绑定数据有效,但未更新
问题描述
我正在尝试使用最新的 Angular 更新跨度中的文本。但是,我不清楚生命周期挂钩和更新在 Angular 中是如何工作的。问题在于fileName
- 我绑定数据并在页面加载时获取初始值。但是,当数据变量更新时,我可以在控制台中看到更改,但组件本身没有更新。
我应该使用一些生命周期方法还是其他方法?我读过:https ://angular.io/guide/lifecycle-hooks并没有让我明白。
<form (ngSubmit)="putToBucket()" class='form-class' >
<label for="image_uploads" >Select Image</label>
<input type='file' id="image_uploads" (change) ='onFileSelected($event)' class='input-button' multiple>
<span > {{fileName }} </span>
<button class='submit-button' type='submit' >Submit</button>
</form>
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
constructor(
private http: HttpClient,
private toastr: ToastrService) { }
urlApi = '//myuri api';
respond;
fileName: Array<any> =['Test']
onFileSelected(event) {
//console.log(event.target.files[0].name)
let name = event.target.files[0].name;
this.fileName.push(name)
console.log(this.fileName)
解决方案
您的 fileName 是一个数组,因此要显示它,您必须在 .html 文件中对其进行迭代,或者您可以将 fileName 更改为字符串并执行如下所示。
export class AppComponent {
fileName="Test";
ngOnInit(){
console.log(this.fileName);
}
onFileSelected(newName){
this.fileName=newName;
console.log(this.fileName);
}
}
.html 文件
<button (click)="onFileSelected('newFile')">change file name</button>
工作演示:演示
推荐阅读
- angular - 显示在 Mat select 中选择的默认选项 - 当 mat 选项值取决于父下拉列表时
- r - 在R闪亮中将fileinput进度条颜色更改为渐变
- android - Kotlin:使用谷歌登录失败
- java - 动态更新键的 Map 值
- python - python中的__getattr__方法
- laravel - Laravel Echo.join 在推送器中抛出错误
- typescript - 我需要使用 moment.js 生成四个特定的时间消息
- php - Laravel 护照阻止用户使用相同的凭据一起登录
- docker - docker hub 私有注册表中的“PARALLEL BUILD”是什么?
- python-3.x - 需要以下问题的图形表示,(例如:直方图、群图等)