【发布时间】:2018-08-31 15:11:10
【问题描述】:
我有一个 Angular 应用程序,它根据另一个输入字段的内容显示和隐藏一个输入字段。现在,当用户在其中输入内容时,我需要对第二个字段进行一些自动格式化。但是当组件加载时该字段是隐藏的,所以我需要检查第一个字段的值以检查是否应该显示第二个字段,然后在它可见时订阅它的 valueChanges。
我的代码如下所示:
export class MyInputComponent implements AfterViewInit {
private subscription = Subscription.EMPTY;
@ViewChild('firstInput', { read: NgControl }}
public firstInput: NgControl;
@ViewChild('secondInput', { read: NgControl }}
public secondInput: NgControl;
public isSecondInputVisible = new BehaviorSubject<boolean>(false);
public ngAfterViewInit() {
this.firstInput.valuesChanges!.subscribe((first) => {
this.isSecondInputVisible.next(first.length > 4);
});
this.isSecondInputVisible.subscribe((isVisible) => {
if (isVisible) {
this.subscription = this.secondInput.valueChanges!.subscribe((value) => {
// do something...
});
} else {
this.subscription.unsubscribe();
}
});
}
}
我想知道是否有办法链接订阅,我不会在代码中有太多缩进和嵌套。 我认为使用 pipe 或许可以做到这一点,但我还没有找到方法。
有没有办法优化订阅部分?
【问题讨论】:
标签: angular rxjs observable behaviorsubject