gpt4 book ai didi

angular - 在 Angular2 中动态更新 [checked]

转载 作者:太空狗 更新时间:2023-10-29 17:55:02 25 4
gpt4 key购买 nike

componentA.ts:

@Input() array;

<input type="checkbox" [checked]="array | contains: value"/>
<label>{{array.length}}</label>

componentB.ts:

@Component({
selector: 'app-component-b',
templateUrl: './app.component-b.html'
})
export class AppComponentB {
array = [1, 2, 3];
}

我更新了一些其他组件中的 array。虽然 label 正确更新了数组的长度,但复选框似乎没有更新。 contains 只是一个简单的管道,用于检查 value 是否是 array 的一部分。我在 contains 管道中放置了一个 console.log 并且仅在页面最初呈现时获得输出,而不是在 array 更改时获得输出。这是为什么?

谢谢..

最佳答案

那是因为如果您使用 push 向数组添加新项,则数组引用不会更改,而纯管道仅在检测到输入值发生纯粹更改时才会执行 (arrayvalue 在你的情况下)

有两种解决方法:

1) 返回新数组

this.array = this.array.concat(4)

this.array = [...this.array, 4];

Plunker

2)使用不纯的管道

@Pipe({name: 'contains', pure: false})
export class ContainsPipe implements PipeTransform {

Plunker

更多详细信息另见

关于angular - 在 Angular2 中动态更新 [checked],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39941185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com