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

Angular > getter vs method in template

Discussão em 'Angular' iniciado por omg4zz, Novembro 6, 2024 às 07:32.

  1. omg4zz

    omg4zz Guest

    To avoid writing logic in the *ngIf of the template for example.

    <div *ngIf="a === 3 && b === 'foo'"></div>

    I usually create ad hoc method for e.g.

    public isOk(): boolean {
    return a === 3 && b === 'foo'
    }


    and the previous code become:

    <div *ngIf="isOk()"></div>

    Is this a good practice?

    is it right to use a method or is it better to use a getter?

    Why should we use one or another?

    pro? cons?

    so, with a getter, it would become:

    public get isOk(): boolean {
    return a === 3 && b === 'foo'
    }


    and the previous code become:

    <div *ngIf="isOk"></div>

    UPDATE:

    After adding signals in Angular, the most performance efficient way to solve the question asked is precisely to use signal and computed because they are not tied to the change detection loop unlike getters and methods (used in the template)

    Official documentation

    export class SampleComponent {

    constructor(private cdr: ChangeDetectorRef) {}

    a = 3;
    b = 'foo'

    asignal = signal(3);
    bsignal = signal('foo');



    get isOkGetter(): boolean {
    console.log('getter');
    return this.a === 3 && this.b === 'foo';
    }

    isOkMethod(): boolean {
    console.log('method');
    return this.a === 3 && this.b === 'foo';
    }

    isOkSignal = computed(() => {
    console.log('signal');
    return this.asignal() === 3 && this.bsignal() === 'foo'
    });

    changeSomething() {
    this.a = 5;
    this.asignal.update(() => 5);
    //Simulate change detection cycle
    this.cdr.markForCheck();
    }

    }


    --

    <div>
    <p>getter: {{ isOkGetter }}</p>
    <p>method: {{ isOkMethod() }}</p>
    <p>signal: {{isOkSignal()}}</p>
    <button (click)="changeSomething()">Change something</button>
    </div>

    Continue reading...

Compartilhe esta Página