为什么这个组件在这个简单的砰砰声中

@Component({
  selector: 'my-app',
  template: `<div>I'm {{message}} </div>`,
})
export class App {
  message:string = 'loading :(';

  ngAfterViewInit() {
    this.updateMessage();
  }

  updateMessage(){
    this.message = 'all done loading :)'
  }
}

扔:

例外:表达式'I'm {{message}} in App@0:5'在被检查后发生了变化。之前的值:'I'm loading:('。当前值:'I'm all done loading:)' in [I'm {{message}} in App@0:5]

当我所做的一切都是更新一个简单的绑定时,我的视图被启动?


当前回答

我认为最简单的解决方法如下:

Make one implementation of assigning a value to some variable i.e. via function or setter. Create a class variable (static working: boolean) in the class where this function exists and every time you call the function, simply make it true whichever you like. Within the function, if the value of working is true, then simply return right away without doing anything. else, perform the task you want. Make sure to change this variable to false once the task is completed i.e. at the end of the line of codes or within the subscribe method when you are done assigning values!

其他回答

为此,我尝试了上面的答案,其中许多在最新版本的Angular(6或更高版本)中都不起作用。

我正在使用材料控制,需要在第一次绑定完成后进行更改。

    export class AbcClass implements OnInit, AfterContentChecked{
        constructor(private ref: ChangeDetectorRef) {}
        ngOnInit(){
            // your tasks
        }
        ngAfterContentChecked() {
            this.ref.detectChanges();
        }
    }

加上我的答案,这有助于解决一些具体问题。

只需将代码移动到要更改共享服务主题的组件的构造函数中

你不能用ngOnInit因为你只是改变了成员变量消息?

如果你想访问子组件@ViewChild(ChildComponent)的引用,你确实需要用ngAfterViewInit来等待它。

一个肮脏的修复方法是在下一个事件循环中调用updateMessage(),例如setTimeout。

ngAfterViewInit() {
  setTimeout(() => {
    this.updateMessage();
  }, 1);
}

你也可以试着把this.updateMessage();在ngOnInit下,像这样:

ngOnInit(): void { 
  this.updateMessage();
}

我认为最简单的解决方法如下:

Make one implementation of assigning a value to some variable i.e. via function or setter. Create a class variable (static working: boolean) in the class where this function exists and every time you call the function, simply make it true whichever you like. Within the function, if the value of working is true, then simply return right away without doing anything. else, perform the task you want. Make sure to change this variable to false once the task is completed i.e. at the end of the line of codes or within the subscribe method when you are done assigning values!