4

let's say I have to following entity

export class Photo {
   public data: Blob;
   public User: string;
}

the following component

@Component({
   template: '<my-other-component [(ngModel)]="photo.data"></my-other-component>'
})
export class MyComponent {
    @Input()
    photo: Photo;

    constructor(private photoService: PhotoService, private cd: ChangeDetectorRef){}

    public deletePhoto(): void {
       this.photoService.deletePhoto(this.photo)
           .subscribe((result: ApiResult) => {

             //if done here, change detection doesn't work
            this.photo = new Photo();
           });

        //if done here, change detection works
        this.photo = new Photo();
   }
}

PhotoService is a service which makes a http delete request.

my-other-component implements ControlValueAccessor

Whenever I change the object I bind to my child component my-other-component within my subscribe method, no change is propagated.

If i call it outside my subscribe method it works and my-other-component is notified about the change.

It doesnt matter if I set photo to NULL or a new instance or just change the property data.

I assume this behavior is by design, but I'd like to know why and how and if can get it to work. Or maybe I'm on the completely wrong track.

I already tried it with ChangeDetectorRef and markForCheck

Any ideas?

EDIT As always ;) Shortly after posting I found the solution. use ChangeDetectorRef but not the method markForCheck. Correct is detectChanges

Changes are not propagated, but the question remains.

Why do I have to trigger change detection manually within an observable?

Arikael
  • 1,989
  • 1
  • 23
  • 60
  • I think you should use @Output with EventEmitter. Here is an example: http://learnangular2.com/outputs/ – Vishal May 17 '17 at 17:50

0 Answers0