【问题标题】:Angular 7: How to keep the variable value updated in html after changes in ts fileAngular 7:如何在 ts 文件更改后保持变量值在 html 中更新
【发布时间】:2019-04-03 14:35:41
【问题描述】:

我有一个在页面加载时传递给 html 的值,但是当我使用其他函数时这个值会发生变化,然后该变量不再在 html 中更新。

我尝试使用 ngModel,但它不起作用,因为我有一个对象数组和一个对象。

html

<div *ngFor="let item of itens">            
     <textarea class="textarea" id="item-textarea" [value]="item.text"> 
     </textarea>
</div>

Ts

public itens:any[] = [];

constructor() {

}

ngOnInit() {
    this.initItens();
    this.changeItens();
}

initItens() {
    let item = new Item();
    item.text = "Hello world";
    return itens.push(item);
}

changeItens() {
    let item = new Item();
    item.text = "Bye bye World";
    return itens.push(item);
}       

我想知道如何在 .ts 文件中更新变量 itens 和 item (item.text) 时始终在 html 中更新它

谢谢。

【问题讨论】:

  • 你能在 HTML 输出中显示值不正确的情况吗?问题中给出的代码似乎给出了正确的结果。请参阅this stackblitz(其中return itens.push(item) 已替换为return this.itens.push(item))。
  • [value]="item.text" 应始终反映该值。我怀疑问题出在代码的另一部分,而不是您在此处发布的内容。
  • 你能用this.itens.push(item)代替itens.push(item)吗?
  • 就是这样!你的编辑不抱怨itens is undefined吗?如果没有,它应该。正确的语法是this.itens。您也可能在控制台中遇到错误。
  • 是的,我们刚刚告诉了你原因:)

标签: javascript angular forms


【解决方案1】:

为什么你的函数返回数组?应该是这样的

initItens() {
    let item = new Item();
    item.text = "Hello world";
    this.itens.push(item);
}

changeItens() {
    let item = new Item();
    item.text = "Bye bye World";
    this.itens.push(item);
}

【讨论】:

  • 呸,如果他们这样做了怎么办?我不认为它会改变任何东西。返回值不被任何东西使用,仅此而已。
  • 没错,itens 数组并没有真正改变,所以值没有改变。
【解决方案2】:

确保引用this.itens,并且在使用*ngFor 时,建议使用解构或Array.slice() 创建数组的新实例

解构示例:

 let item = new Item();
 item.text = "Hello world";
 this.itens = [...this.itens, item];

Slice() 示例:

 let item = new Item();
 item.text = "Hello world";
 this.itens = this.itens.slice();
 this.itens.push(item);

这是ngFor的一个很好的教程

https://malcoded.com/posts/angular-ngfor/

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 2017-04-07
    • 2019-12-17
    • 1970-01-01
    • 2019-07-13
    • 2020-02-13
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多