问题描述:
在Angular 6中,当使用ngFor指令时,计算属性绑定不起作用。
解决方法:
在组件中,使用Getter函数来返回计算属性的值。例如:
@Component({
selector: 'app-example',
template: `
{{ getComputedValue(item) }}
`
})
export class ExampleComponent {
items = [1, 2, 3];
getComputedValue(item) {
// 计算属性的逻辑
return item * 2;
}
}
创建一个自定义管道来计算属性的值,然后在ngFor指令中使用该管道。例如:
@Pipe({ name: 'computedValue' })
export class ComputedValuePipe implements PipeTransform {
transform(item: any): any {
// 计算属性的逻辑
return item * 2;
}
}
在模板中使用该管道:
@Component({
selector: 'app-example',
template: `
{{ item | computedValue }}
`
})
export class ExampleComponent {
items = [1, 2, 3];
}
通过使用Getter函数或自定义管道来计算属性的值,可以解决在ngFor中计算属性绑定不起作用的问题。