简体   繁体   中英

How to disable change detection in parent component in a communication from parent to child

I am having parent to child communication and both are rendering some set of data. There is an requirement that on click(click) of some event of parent component i want to disable the change detection cycle because that change is not affecting my child.

Let say

<button click="myMethod()"></button>
<child-component [somedata] ="somedata"> </child-component>

export ParentComponent {
//methodCall() {
//this method has been called
// i want to disable change detection cycle here}

}

I have tried earlier ngZone but after clicking there is no way to stop that cycle only we can halt the screen by timer. Also ChangeDetectionStrategy.OnPush is not working.Someone please help.

You should use the

ChnageDetectionStrategy.OnPush

method for this purpose.

You can annotate your child component like this:

@Component({
  selector: 'tooltip',
  template: `
    <h1>{{config.position}}</h1>
    {{runChangeDetection}}
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TooltipComponent  {

  @Input() config;

  public test() {}
}

OnPush strategy ensures that Change detection will only run for this component when the input property of this component changes.

Create some service where you can store your data. In this service add field as observable, which send boolean. Subscribe to this observable wherever you need.

Snippet from service:

  access$ = new BehaviorSubject(true);
  changeAccess(state: boolean) {
    this.access$.next(state);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM