1

Buenas estoy trabajando en Angular universal y tengo la siguiente función

private validateBox() {
    const divHeight: any = document.getElementById('product-detail-images').getBoundingClientRect();
    if (divHeight) {
        if (divHeight.top > -2491) {
            this.isAbsolute = false;
            this.cd.markForCheck();
        } else {
            this.isAbsolute = true;
            this.cd.markForCheck();
        }
    }
}

El problema es que document.getElementById('product-detail-images').getBoundingClientRect() me da error en consola. error TS2531: Object is possibly 'null'.

2 respuestas 2

1

Es un error de compilación, porque no estás comprobando si el elemento existe o no, pero tienes una comprobación sobre si la altura es 0 o no. Deberías comprobarlo así:

private validateBox() {
    const divHeight: any = document.getElementById('product-detail-images')!.getBoundingClientRect();
        if (divHeight.top > -2491) {
            this.isAbsolute = false;
            this.cd.markForCheck();
        } else {
            this.isAbsolute = true;
            this.cd.markForCheck();
        }
    }
}

El símbolo de admiración es el operador "check not null", si la llamada a document.getElementById es null, no provocará un error sino que hará que div valga null

1
  • Me sirvió de mucha ayuda gracias
    – beaag58
    el 27 abr. 2020 a las 16:46
0

Esto se debe a que seguramente tienes activado en tu fichero tsconfig el flag strict null checks. Esto es una feature para evitar errores en runtime.

private validateBox() {
    const div: Element | null = document.getElementById('product-detail-images');
    if (div) {
        const divHeight: any = document.getElementById('product-detail-images').getBoundingClientRect();
        if (divHeight.top > -2491) {
            this.isAbsolute = false;
            this.cd.markForCheck();
        } else {
            this.isAbsolute = true;
            this.cd.markForCheck();
        }
    }
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.