Angular 如何将子组件的elementRef放入其自身中?

问题描述 投票:0回答:1

我有一个父组件和一个子组件。

@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( [] )
    });
 }
}

模板:

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

子组件

@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);
 }
 
}

子组件模板:

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

我的问题是,某些情况下,当父组件在 ngOnInit() 中做了很多事情时,在子组件生命周期钩子 AfterViewInit 中, this.elementRef 仍然未定义,因为首先处理子组件,而 elementRef 没有获得有价值的 elementRef时间。

如何避免这种情况?我需要真正的 elementRef。

angular nested viewchild elementref
1个回答
0
投票

当你在组件中时,你可以直接注入elementRef:

elementRef = inject(ElementRef)
© www.soinside.com 2019 - 2024. All rights reserved.