Angular 4 - “Expression has changed after it was checked” error while using NG-IF

后端 未结 6 1556
天命终不由人
天命终不由人 2020-12-14 21:05

I setup a service to keep track of logged in users. That service returns an Observable and all components that subscribe to it are notified (so

6条回答
  •  青春惊慌失措
    2020-12-14 21:15

    Declare this line in constructor

    private cd: ChangeDetectorRef
    

    after that in ngAfterviewInit call like this

    ngAfterViewInit() {
       // it must be last line
       this.cd.detectChanges();
    }
    

    it will resolve your issue because DOM element boolean value doesnt get change. so its throw exception

    Your Plunkr Answer Here Please check with AppComponent

    import { AfterViewInit, ChangeDetectorRef, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
    import { Subscription } from 'rxjs/Subscription';
    
    import { MessageService } from './_services/index';
    
    @Component({
        moduleId: module.id,
        selector: 'app',
        templateUrl: 'app.component.html'
    })
    
    export class AppComponent implements OnDestroy, OnInit {
        message: any = false;
        subscription: Subscription;
    
        constructor(private messageService: MessageService,private cd: ChangeDetectorRef) {
            // subscribe to home component messages
            //this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });
        }
    
        ngOnInit(){
          this.subscription = this.messageService.getMessage().subscribe(message =>{
             this.message = message
             console.log(this.message);
             this.cd.detectChanges();
          });
        }
    
        ngOnDestroy() {
            // unsubscribe to ensure no memory leaks
            this.subscription.unsubscribe();
        }
    }
    

提交回复
热议问题