1 year ago

#348133

test-img

3gwebtrain

How to avoid Manual detectChanges in component

I am getting an error, unless if i do not do the manual changes deduction with hook. how to avoid this? instead what hook should i use in this scenario?

here is my code:

import {
  Component,
  ComponentFactoryResolver,
  ComponentRef,
  ViewChild,
  ViewContainerRef,
  AfterViewInit,
  OnChanges,
  SimpleChanges,
  SimpleChange,
  AfterContentChecked,
  ChangeDetectorRef,
} from '@angular/core';
import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit, OnChanges {
  @ViewChild('vrf', { read: ViewContainerRef }) vrf: ViewContainerRef;
  name = 'Angular';
  constructor(
    private containerFactoryResolver: ComponentFactoryResolver,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnChanges(changes: SimpleChanges) {
    console.log('hi'); //not works
  }

  ngAfterViewInit() {
    const component =
      this.containerFactoryResolver.resolveComponentFactory(HelloComponent);
    this.vrf.createComponent(component);
    this.cdr.detectChanges();
  }
}

Live Demo

Thanks in advance.

angular

angular-changedetection

0 Answers

Your Answer

Accepted video resources