Initialize a model signal with the value of an input signal

Discussão em 'Angular' iniciado por Taekwondavide, Janeiro 16, 2025.

  1. I'm using the new Angular model input feature in order to have a two-way binding between parent and child components:

    Parent component (Person):

    export class PersonComponent {
    person = model.required<Person>();
    }


    <app-person-details [(person)]="person" />


    Child component (PersonDetails):

    export class PersonDetailsComponent {
    person = model.required<Person>();
    }


    The parent component currently takes its input from the route resolver, however I want to make the component reusable and I'd like to decouple the parent component's input and the model signal so that:

    • the parent component can receive a required person input signal
    • the input is used to set the value of the required personModel model signal
    • the personModel signal can be updated by the child component without affecting the person signal

    export class PersonComponent {
    person = input.required<Person>();
    personModel = model.required<Person>();

    updatePersonModel = effect(() => {
    this.personModel.set(this.person());
    })
    }


    The main issue is that I need to set an initial value to personModel, which cannot be undefined. I tried by initializing personModel inside the constructor and inside ngOnInit but these solutions don't work. Does anyone have any solution that does not involve adding undefined to the signal type or removing TypeScript's strict mode?

    Continue reading...

Compartilhe esta Página