针对 ExpressionChangedAfterItHasBeenCheckedError 的信号修复

问题描述 投票:0回答:1

运行以下代码时,我收到可怕的“ExpressionChangedAfterItHasBeenCheckedError”错误:

import { Component, OnInit, Input } from '@angular/core';
import { StickyMenuWithoutSubItems } from "../../../shared/interfaces/data/sticky-menus/sticky-menu-without-subitems-interface";
import { Router  } from '@angular/router';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-content-sticky-menu-without-sub-items',
  templateUrl: './content-sticky-menu-without-sub-items.component.html',
  styleUrls: ['./content-sticky-menu-without-sub-items.component.scss']
})
export class ContentStickyMenuWithoutSubItemsComponent implements OnInit {

  constructor(private router: Router, private route: ActivatedRoute){

  }

  subItemIdInFocus!: string;
  @Input() detail!: StickyMenuWithoutSubItems;
  urlPath: string = this.router.url.split("#")[0]; //Remove any querystrings that might already be present in the url
  menuOpen: boolean = false;


  ngOnInit(): void {

    // If there is a hash value in the address bar then animate down to it
    const hash = this.route.snapshot.fragment;
    if (hash) {
      const element = document.getElementById(hash);
      element!.scrollIntoView({ behavior: "smooth" });
    }
  }

  returnZero() {
    return 0
    }

  scrollToArea($event: Event, id: string){

    // Force close the menu
    this.menuOpen = false;

    // Prevent the actual a href from actioning
    $event.preventDefault();

    // Update the url so if the user reloads the page they'll automatically be anchored down to the section they were viewing
    window.history.pushState(null, "", `${this.urlPath}#${id}`);

    // Perform the animation scroll
    const element = document.getElementById(id);
    element!.scrollIntoView({ behavior: "smooth" });
  }

  onIntersecting(id: string) {
      this.subItemIdInFocus = id;
  }

}

我假设这与“subItemIdInFocus”变量有关。

因此,考虑到这一点,我尝试根据我在文章中读到的内容将其更新为以下内容:

subItemIdInFocus = signal("");

onIntersecting(id: string) {
      this.subItemIdInFocus = id;
  }

但是这样做时我收到以下构建错误:

This comparison appears to be unintentional because the types 'WritableSignal<string>' and 'string' have no overlap

我在这里缺少什么?

angular signals
1个回答
0
投票

改成,

set
方法设置值!我们将
string
的类型分配给
WritableSignal<string>
,这会产生问题

当我们想要设置一个值时,我们可以使用

set

  onIntersecting(id: string) {
      this.subItemIdInFocus.set(id);
  }
© www.soinside.com 2019 - 2024. All rights reserved.