0

I have some code I have been working on but I can't find anything on this on google. Basically I want to pass a number that represents an ID to my component to be used when it is instantiated.

I don't know what to try tbh

<div class="row">
    <div class = "col-xs-12">
        <app-server *ngFor  = "let server of servers"></app-server>
    </div>
</div>

The constructor or ngOnInit will be passed a parameter that is a number.

1 Answers1

2

Inside the component of app-server, you will need import { Component, Input } from '@angular/core';

Then we can use @Input to let the component know you'll be receiving this variable's value through the template.

So the component will look like

//... other imports 
import { Component, Input } from '@angular/core';

@Component({
    selector: "app-server",
    templateUrl: "...,
    styleUrls: ["..."]
})
export class AppServerComponent {

    @Input id: number;

    //.. rest of code

}

And in your template, you supply the value like so:

<app-server *ngFor="let server of servers" [id]="desired_id_value"></app-server>
JamieT
  • 1,177
  • 1
  • 9
  • 19
  • So we cannot just pass a value? That makes sense but I want to make sure. – user3851290 Jun 17 '19 at 19:09
  • @AlexanderStaroselsky in this case, why would I want to pass the entire server object to itself – user3851290 Jun 17 '19 at 19:10
  • @user3851290 Do you mean whether you can just pass down the entire `server` item? If so, yes you can, you can pass as little or as much as you need. You just need to update the type of @Inpu(). I don't why you would need to pass down one or another, I was just explaining that you can pass as little or as much as you need depending on your requirements and application using @Input() in the child component. – Alexander Staroselsky Jun 17 '19 at 19:10
  • I am used to C++. Assuming your format what if I wanted to say [id] = servers[server] which I know won't work because "server" is an object so how do I access the index? – user3851290 Jun 17 '19 at 19:24
  • @user3851290 yes, you can pass a value or a constant. ie `` – JamieT Jun 17 '19 at 19:34