angular - <ng-content> kullanırken ViewChild.nativeElement null


ViewChild.nativeElement’imin tüm yaşam döngüsü kancalarında null olduğu bir sorunum var. Bileşenim şöyle görünüyor:

@Component({
    selector: 'connector-component',
    template: `
    <ng-container>
      <ng-content></ng-content>
    </ng-container>
  `
})
export class ConnectorComponent implements AfterContentInit {
    @ContentChild('ccdComponent') ccdComponent: ElementRef;

    ngAfterContentInit() {
        console.log(this.ccdComponent); // works as expected
        console.log(this.ccdComponent.nativeElement); // null :(
    }
}

Bu bileşen şöyle çağrılacaktır:

<connector-component>
    <ccd-search #ccdComponent>
    </ccd-search-component>
</connector-component>

Belirlemek istediğim şey, #ccdComponent etiket adlıdır - bu durumda, ccd-search. connector-component'ün, #ccdComponent etiketine sahip bir çocuk bileşeni içereceğini garanti edebiliriz. Ve her durumda, ElementRef yaşam döngüsü kancasında doludur, ancak nativeElement null'dır.

Bunu nasıl yapabilirim?

Cevap #1

@ContentChild, component örneğini okuma konusunda varsayılan bir davranışa sahiptir. Bu nedenle, <ccd-search> örneğinin nativeElement adında bir özelliği yoktur, bu yüzden bu değer her zaman undefined olacaktır.

Sorguya ne okumak istediğinizi söylemelisiniz.

@ContentChild('ccdComponent', {read: ElementRef}) ccdComponent: ElementRef;

ccdComponent değeri ngAfterContentInit çağrılmadan önce ayarlanacaktır.

https://angular.io/api/core/ContentChild

Angular'ın undefined bir elementi saran bir ElementRef nesnesi oluşturduğunu hiç görmüş olduğumu sanmıyorum. Bir dahaki sefere thing.nativeElement undefined olduğunda, thing'a bir kez daha bakın ve onun bir ElementRef olduğundan emin olun. Angular ya bir ElementRef oluşturur ya da oluşturmaz.