1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

How can I change the text using the new ContentChild signal API?

Discussão em 'Angular' iniciado por mohammed fahimullah, Outubro 13, 2024.

  1. I'm trying to migrate my Angular component to use the new ContentChild signal API, but I'm encountering some TypeScript issues.

    Here's my existing code using the traditional @ContentChild decorator:

    // child-component.ts
    import { Component, ContentChild, ElementRef, AfterContentInit } from '@angular/core';

    @Component({
    selector: 'app-child',
    templateUrl: './child-component.html',
    })
    export class ChildComponent implements AfterContentInit {
    @ContentChild('headerTitle', { static: true }) headerTitleContent!: ElementRef; // Access projected title
    @ContentChild('headerSubtitle', { static: true }) headerSubtitleContent!: ElementRef; // Access projected subtitle
    @ContentChild('navbar') navTitle!: ElementRef; // Access navbar

    constructor() {
    console.log(this.headerTitleContent); // Access title element
    }

    ngAfterContentInit() {
    this.headerSubtitleContent.nativeElement.textContent = 'Enjoy a customized experience!';
    }
    }


    I want to achieve the same functionality using the new ContentChild signal API as follows:

    import { Component } from '@angular/core';
    import { contentChild, effect } from '@angular/core';

    @Component({
    selector: 'app-child',
    templateUrl: './child-component.html',
    })
    export class ChildComponent {
    private headerTitleContent = contentChild<ElementRef<HTMLAnchorElement>>('headerTitle');
    private headerSubtitleContent = contentChild<ElementRef<HTMLAnchorElement>>('headerSubtitle');
    private navTitle = contentChild<ElementRef<HTMLElement>>('navbar');

    constructor() {
    console.log(this.headerTitleContent); // Access title element
    effect(() => {
    if (this.headerSubtitleContent()) {
    this.headerSubtitleContent().nativeElement.textContent = 'HI this is my name'; // Issue occurs here
    }
    });
    }
    }


    ISSUE The left-hand side of an assignment expression may not be an optional property access. [​IMG]

    Continue reading...

Compartilhe esta Página