Angular How to put elementRef of child component into itself?

85 views Asked by At

I have a parent component, with a child component.

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrl: './parent.component.scss'
})
export class ParentComponent implements OnInit {
  private formBuilder: FormBuilder = inject(FormBuilder);
  parentForm: FormGroup;
  @ViewChild('checkListRef', { read: ElementRef, static: true }) elementRef: ElementRef; 

 ngOnInit() {
    this.parentForm = this.formBuilder.group({
      child: this.formBuilder.control( [] )
    });
 }
}

The Template:

<form [formGroup]="parentForm" (ngSubmit)="onSubmit(parentForm)" novalidate autocomplete="off">
  <app-child #childRef [elementRef]="elementRef">
  </app-child>
</form>

The Child component

@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrl: './child.component.scss'
})
export class ChildComponent implements OnInit, AfterViewInit {
 private formBuilder: FormBuilder = inject(FormBuilder);
 childForm: FormGroup;
 @Input() elementRef: ElementRef;
 
 ngOnInit() {
    this.childForm = this.formBuilder.group({
      ...
    });
 }

 ngAfterViewInit() {
  // at this point I would like to use the elementRef but it some cases undefined
  console.log(this.elementRef);
 }
 
}

The Child component template:

<form [formGroup]="childForm" (ngSubmit)="onSubmit(childForm)" novalidate autocomplete="off">
  ...
</form>

My problem is, some cases when the parent component did a lot of thing in the ngOnInit(), in the child component lifecycle hook AfterViewInit the this.elementRef remains undefined because processing the child component first and the elementRef did not get valuable elementRef in time.

How can I avoid this? I need the real elementRef.

1

There are 1 answers

0
Matthieu Riegler On

You can inject the elementRef directly when you're in a component:

elementRef = inject(ElementRef)