我正在尝试使用最新的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)
答案 0 :(得分:1)
您的fileName是一个数组,因此要显示它,您必须在.html文件中对其进行迭代,也可以将fileName更改为string并按如下所示进行操作。
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>
正在运行的演示:demo
答案 1 :(得分:1)
fileName : Array<any> = [];
onFileSelected(event){
console.log(event.target.files[0].name)
let name = event.target.files[0].name;
this.fileName.push(name)
console.log(this.fileName)
}
<input type='file' id="image_uploads" (change) ='onFileSelected($event)' class='input-button' multiple>
<span *ngFor="let list of fileName">{{list}}</span>
答案 2 :(得分:0)
请尝试在您的组件中实现onPush
或ChangeDetectionStrategy
这样做将指示Angular仅在将新引用传递给组件和子树时(而不是简单地对数据进行突变时)对这些组件及其子树运行更改检测。
在更新变量并希望其反映在html中时运行this.ref.markForCheck()
或this.ref.detectChanges()
请检查以下链接以获取更多信息