【问题标题】:NgIf not triggered on value-change in Subject Subscription主题订阅中的值更改未触发 NgIf
【发布时间】:2021-10-09 11:57:19
【问题描述】:

在 Subject scubrsciption 中更改值时不会触发 NgIf。 控制台为 responseState 打印正确的所需值。 responseStateSubject 是通过其他组件的输入给出的。 我已经用 NgOnChanges 实现了它,但这对我来说太过分了。

组件代码:

   @Input() responseStateSubject: Subject<RequestResponseState>;
        
   ngOnInit(): void {
             
    
   this.responseStateSubject.subscribe((x) => {
        //****  This is the relevant part, it does set the  property and prints the corresponding value. *//
    
                this.responseState = x as RequestResponseState;
                console.log(this.responseState);
    
        //****//
                if (x != undefined && x != null) {
                  this.mainWrapper.nativeElement.classList.add("open-main-wrapper");
                  if (x.requestEnum != this.requestResultBaseEnum.Loading) {
                    this.utilsS.scrollElementIntoView("response-main-wrapper");
                  }
                } else {
                  if (this.mainWrapper != null) {
                    this.mainWrapper.nativeElement.classList.remove(
                      "open-main-wrapper"
                    );
                  }
                }
              });
    }

组件html:

<div #mainWrapper id="response-main-wrapper" class="flex-center">
  <div
    *ngIf="responseState != null && responseState != undefined"
    id="message-main-container"
  >
    <hr class="grey-hr" />
</div>
</div>

【问题讨论】:

  • 你在组件中使用什么变化检测策略?

标签: html css angular typescript subject


【解决方案1】:

使用 ChangeDetectorRefdetectChanges() 方法为我解决了这个问题。

【讨论】:

  • 您应该使用异步管道订阅 html 中的主题,而不是调用 detectChanges(),并在管道中的水龙头中执行其他操作。否则你会因为不取消订阅 observable 而冒内存泄漏的风险。
  • @ThomasRenger,我正在取消订阅 NgOnDestroy 挂钩中的订阅。应该没问题吧?
猜你喜欢
  • 2021-10-05
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
相关资源
最近更新 更多