首页 > 解决方案 > 角; 当我在脚本中更新变量时如何重新渲染组件数据。绑定数据有效,但未更新

问题描述

我正在尝试使用最新的 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)

我看到的例子: 在此处输入图像描述

标签: javascriptangulardata-bindingrender

解决方案


您的 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>

工作演示:演示


推荐阅读