1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Why doesn't a component style apply to a dynamically inserted element?

Discussão em 'Angular' iniciado por D M, Novembro 5, 2024 às 19:42.

  1. D M

    D M Guest

    I am programmatically appending a new element to an existing element in my component, but the styles associated with the .target class defined in the component's styles do not appear to apply to the new element. Why are the styles not applied?

    import { AfterViewInit, Component, ElementRef, inject, viewChild } from '@angular/core';

    @Component({
    selector: 'app-foo',
    standalone: true,
    template: `
    <div #container>
    <div class="target">Pre-existing .target element</div>
    </div>
    `,
    styles: `
    .target {
    background-color: rgba(255, 0, 0, 0.5);
    }
    `,
    })
    export class FooComponent implements AfterViewInit {
    private readonly container = viewChild.required<ElementRef<HTMLDivElement>>('container');

    ngAfterViewInit() {
    if (this.container().nativeElement) {
    const target = document.createElement('div');
    target.innerText = 'Dynamic .target element';
    target.classList.add('target');
    this.container().nativeElement.appendChild(target);
    }
    }
    }


    [​IMG]

    Continue reading...

Compartilhe esta Página