Search code examples
arraysangulartypescriptcomponents

How to set positions in an array of specific component with its selector using Angular?


I'm very new to Angular and I would like to know if it is possible to set positions of an array, that is already declared as empty in one component, with its selector in another component.

For example, lets say I have component named "array" and in the array.component.ts file I'm declaring and empty array:

export class ArrayComponent {

array: number[] = [];

}

In my main "app" component I would like to use the "array" component and set its values with its selector:

app.component.html:

<app-array array="10"></app-array>

Is this possible? And if yes, how should I implement it? Should I use Attribute directives or?

Thanks in advance.

I didn't tried any solutions, because I'm not sure how to implement it exactly.


Solution

  • You can use the @Input() decorator to pass information from a parent component to a child component

    array.component.ts

    export class ArrayComponent {
      @Input() array: number[] = [];
    }
    

    app.component.html

    <app-array [array]="[10]"></app-array>
    

    Note: This will pass an array of value [10] into the array variable


    To instead generate an array of length 10, you could build your array in your parent component and pass this to your child. For example:

    array.component.ts

    export class ArrayComponent {
      @Input() array: number[] = [];
    }
    

    app.component.html

    <app-array [array]="parentArray"></app-array>
    

    app.component.ts

    export class AppComponent {
      parentArray: number[] = [];
    
      ngOnInit() {
        this.parentArray = this.buildArrayOfNumbers(10)
      }
    
      buildArrayOfNumbers(length: number): number {
        return Array.from({length}, (_, i) => i + 1)
      }
    }