【发布时间】:2020-04-17 12:31:41
【问题描述】:
上下文
一个业务组件A依赖于一个业务服务,它说:
true:所有可折叠组件都应默认打开。
false:默认关闭所有可折叠组件。
A 通过单向属性绑定到多个技术子组件 B 传递此知识(计算,而不是存储值),这些子组件定义了可折叠组件(其内容是特定业务组件的投影)。
当 A 和 B 首次渲染时,绑定被解析并且 B 接收到知识:可折叠组件知道它们是否应该显示他们的内容或隐藏它。尽管如此,如果用户愿意,他们仍然提供一个按钮来显示或隐藏内容。
注意:可折叠组件不会注入服务本身来直接访问知识,因为它是业务服务,是技术组件。
问题
A中的一个动作之后,我想“重新解析”与B的属性绑定,所以我希望A通过再次向 B 提供服务知识,从而覆盖用户的任何操作(例如:如果他打开了一个默认关闭的可折叠组件,我希望它恢复到默认状态,所以关闭) .
最简单的解决方案是重新渲染组件(销毁/创建),但我不希望这样做,因为:
1)我不希望用户看到由于组件的破坏/渲染而导致的闪烁。
2) 除此问题外,没有充分的理由重新渲染组件。
代码
@Component({
selector: 'business-parent',
template: '
<generic-collapsable-component [opened]="businessHelper.conditionA">
// A business-child component
</generic-collapsable-component>
// More generic-collapsable-component
'
})
export class BusinessParentComponent {
constructor(private businessHelper: BusinessHelper) {
}
onBusinessAction() {
// Here I do some business stuff...
// And I want to force the binding [opened] to re-execute its default value, so I want GenericCollapsableComponent.opened = businessHelper.conditionA, and not what I currently have, which is the value of the last GenericCollapsableComponent.switch() I called.
}
}
@Component({
selector: 'generic-collapsable-component',
template: '
<button (click)="switch()">Switch to show or hide content</button>
<div [ngClass]="{'is-hidden': !isOpen()}"
<ng-content></ng-content>
</div>
'
})
export class GenericCollapsableComponent {
@Input() opened: boolean; // Is intialized by the parent component but can be modified by the inner switch() method called in the template.
constructor() {
}
switch(): void {
this.opened = !this.opened;
}
isOpen(): boolean {
return this.opened;
};
}
解决方案
- 重新渲染组件:否。
- 绑定一个函数 () => boolean 来设置初始值并使用另一个私有布尔值来响应用户操作:这是我所做的并且它有效,但它不是理想。
【问题讨论】:
-
你能创建一个堆栈闪电战来显示这个问题吗?帮助进行现场演示会容易得多。
-
有时间我会试试的。
标签: angular typescript components property-binding