Angular 为什么该值不更新?
我遇到了一个问题,我正在为数组中对象的属性赋值(通过动态变量)。变量更改时,值不会更新。为什么它不更新,有没有其他方法可以实现它,使它更新Angular 为什么该值不更新?,angular,Angular,我遇到了一个问题,我正在为数组中对象的属性赋值(通过动态变量)。变量更改时,值不会更新。为什么它不更新,有没有其他方法可以实现它,使它更新 import { Component, OnInit } from '@angular/core'; @Component({ selector: 'my-app', styleUrls: ['./app.component.scss'], templateUrl: './app.component.html' }) export class
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
styleUrls: ['./app.component.scss'],
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
name = 'Brian';
people = [{ name: this.name }];
ngOnInit() {
setTimeout(() => {
this.name = 'Eric';
console.log(people[0].name); // Brian
}, 5000);
}
}
您正在更新此.name。您还必须更新
people
,因为name:this.name
不是引用
setTimeout(() => {
this.name = 'Eric';
this.people = [{ name: this.name }];
console.log(people[0].name); // Eric
}, 5000);