Search code examples
arraysangular

Where can I fill an array in Angular?


I am following a course, but I think that is using an old version of angular, the code that should work, does not work in my case, I keep having an empty list (<li>No items</li>).

I use the following parts of code :

app.component.html :
<app-test>[testList]="testset"</app-test>

app.module.ts :
// in declarations added : TestComponent

app.component.ts :
export class AppComponent {
  testset: string[] = ['Test 1', 'Test 2', 'Test 3', 'Test 4' ];
  title = 'test in Angular';
}

test.component.html :
<u>
  @for (item of testList; track item ) {
  <li>{{ item }}</li>    
} @empty {
<li>No items</li>
}
</u>

test.component.ts :
//  selector: 'app-test',
export class TestComponent {
  @Input() testList: string[] = []; 
  
// I know here the following is working, but that is not what was expected:
// @Input() testList: string[] =  ['Test 1', 'Test 2', 'Test 3', 'Test 4' ];
}

Is this because this is a change in new angular versions, or am I using a wrong place to fill the array ?

testset: string[] = ['Test 1', 'Test 2', 'Test 3', 'Test 4' ];
(in the export part in app.component.ts)

My goal is to understand how the following code should work :

<app-test>[testList]="testset"</app-test>

(in app.component.html)


Solution

  • testList should be an attribute.

    See more. https://angular.dev/guide/components/inputs

    app.component.html :

    <app-test [testList]="testset"> </app-test>