Is `(input)="true"` idiomatic for Angular OnPush components?

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

  1. I want to disable button if no files selected. I have the following template in OnPush component (Angular v19):

    Events
    <div>
    @for (item of [1, 2, 3, 4]; track $index) {
    <input (input)="true" #file type="file" />
    <button type="button" [disabled]="!file.files!.length" (click)="onAdd2($index, file.files!)">E{{$index}}</button>
    }
    </div>


    I added (input)="true" to trigger change detection, but this doesn't feel idiomatic.
    But alternative using signals doesn't work as expected (buttons are not initially disabled) and feel even less idiomatic and requires more code.

    Signals
    <div>
    @for (item of [1, 2, 3, 4]; track $index) {
    <input (input)="getSignal($index).set(!file.files!.length)" #file type="file" />
    <button type="button" [disabled]="getSignal($index)()" (click)="onAdd2($index, file.files!)">S{{$index}}</button>
    }
    </div>


    @Component({
    selector: 'app-results',
    standalone: true,
    imports: [],
    templateUrl: './results.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class ResultsComponent {
    readonly signals: WritableSignal<boolean>[] = [];

    getSignal(i: number): WritableSignal<boolean> {
    return this.signals ??= signal(false);
    }

    onAdd2(i: number, arg0: FileList) {
    console.log(i, Array.prototype.map.call(arg0, x => x.name));
    }
    }


    What would you suggest?

    Continue reading...

Compartilhe esta Página