Issue
I want to use signals with @Input but not works.
I builded a table component with some @Inputs, but i want to use it with signals.
Something like:
export class TableComponent {
@Input() headers = signal<any[]>([]);
@Input() keys = signal<any>([]);
@Input() data = signal<any[]>([]);
}
How i set the signal value with the value pass into input? Have another approach to make it?
Solution
Signals can be used like any other input. The code you posted is not really wrong, but there must be a mistake somewhere else in the code. And the reason can be that you initialize your signal inputs in TableComponent. If you want to use them like any other input, you would initialize (create) the signals outside of the TableComponent and insert them.
See stackblitz example here: https://stackblitz.com/edit/stackblitz-starters-kfkauw?file=test%2Ftest.component.ts
The following code is a full working solution bases on Angular v16.2:
app.component.ts:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
parentSignal = signal('Value set in App Component');
}
app.component.html:
<div>
<app-test [childSignal]="parentSignal"></app-test>
</div>
test.component.ts:
import { Component, Input, Signal } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
})
export class TestComponent {
@Input() childSignal?: Signal<string>;
}
test.component.html:
<div *ngIf="childSignal">{{ childSignal() }}</div>
Remarks:
- If want to keep the signals inside of the child component (TableComponent in your case) and you only want to update the value of the signals by the input binding, you can achieve that by using private signals inside of the component and by using getters and setters to update the values/retrieve the values.
- You should not use 'any'. By using any, you loos the benefits, TypeScript offers.
Answered By - Konstantin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.