Is it OK to use a signal as component Input in Angular?

Discussão em 'Angular' iniciado por brando, Dezembro 6, 2024.

  1. brando

    brando Guest

    In the following mock-up I use a signal as an input to a component. It works. But I am wondering if this is the proper use of a signal. Seems....weird.

    The follwing is a service that maintains a list of My Friends:


    import {
    Injectable,
    signal
    } from '@angular/core';

    export interface MyFriend {
    name: string;
    age: number;
    }

    @Injectable({
    providedIn: 'root'
    })
    export class MyFriendsService {
    myFriends = signal < MyFriend[] > ([{
    name: 'Bob',
    age: 34,
    },
    {
    name: 'Julie',
    age: 30,
    },
    {
    name: 'Martin',
    age: 25,
    },
    ]);
    }

    The folowing is a Friend Detail Component that shows the detail of a particular friend:


    import {
    Component,
    Input,
    computed,
    signal
    } from '@angular/core';
    import {
    MyFriend,
    MyFriendsService
    } from './my-friends.service';

    @Component({
    selector: 'app-friend-detail',
    templateUrl: './friend-detail-component.html',
    })
    export class FriendDetailComponent {
    @Input() name = signal('Bob');
    friendDetail = computed < MyFriend > (() => {
    const friend = this.myFriendsService
    .myFriends()
    .filter((friend) => friend.name === this.name());
    if (friend.length > 0) {
    return friend[0];
    }
    return {
    name: '',
    age: 0,
    };
    });
    constructor(private myFriendsService: MyFriendsService) {}

    The following component simply uses the FriendDetailComponent:


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

    @Component({
    selector: 'app-some-component',
    template: `<app-friend-detail [name]="selectedName"></app-friend-detail>`,
    })
    export class SomeComponent {
    selectedName = signal < string > ('Julie');
    }

    As I said, this WORKS. But...is this a proper way to be using a signal in angular?

    FYI, I realize that the FriendDetailComponent should be more "dumb" and just accept the input of the FriendDetail info (it need not use signals)...but I did this mock-up as a way to explain a pattern I fell into within the context of a more complex situation.

    Continue reading...

Compartilhe esta Página