【问题标题】:unable to show button on first load with ngIF首次使用 ngIF 加载时无法显示按钮
【发布时间】:2023-01-18 18:00:10
【问题描述】:

我试图在编辑输入表单时显示一个按钮。我在页面加载时隐藏该按钮,它会在我编辑任何输入字段时显示。每当我编辑它时,我都会突出显示输入框。每当我编辑我的输入字段时,我都会收到错误消息 “NG0100:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'false'。当前值:'true'”

该按钮仍然不会出现。然而,当我点击浏览器的随机位置时,我的按钮就会出现。我可以知道这里的问题是什么吗?

TS

button: boolean;

ngOnInit(): void{
this.button = false;
}

highlight(input: string): string{
    //color...
    if (input.dirty) {
      //color
      this.button= true;
    }
    return color;
  }

网页格式


<button *ngIf="button" label='Submit'>

【问题讨论】:

  • highlight 什么时候被调用?

标签: angular typescript primeng


【解决方案1】:

你可以尝试使用ChangeDetectorRef。它运行一个额外的变化检测周期,因此应该消除您提到的错误:

constructor(private cdRef: ChangeDetectorRef){}

button = false;

highlight(input: string): string{
    //color...
    if (input.dirty) {
        //color
        this.button = true;
        this.cdRef.detectChanges(); // Add this additional line of code
    }
    return color;
}

【讨论】:

    猜你喜欢
    • 2018-09-02
    • 1970-01-01
    • 2014-06-12
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    相关资源
    最近更新 更多