0

Let's say I have three components like these ones here in my template

<app-student-dave></app-student-dave>
<app-student-olga></app-student-olga>
<app-student-jason></app-student-jason>

Now I have an array with all these names. So instead of using the names directly, I want to use the array. Something like this:

<app-student-{{myArray[selectedName]}}></app-student-{{myArray[selectedName]}}>

But string interpolation does not work this way. Any idea how implement this in angular2 and above?

2 Answers 2

2

Why not use @Input to pass the name of the student?

You can do something like this

export class StudentComponent {
 @Input() studentName:string;
 //....
}

And you can use it like this

  <app-student [studentName]="dave"></app-student>
  <app-student [studentName]="olga"></app-student>
  <app-student [studentName]="jason"></app-student>

You can refactor it further if you have an array like this

 studentNames:string[] = ['dave','olga','jason'];

And use a *ngFor in your template.

 <div *ngFor="let studName of studentNames>
      <app-student [studentName]="studName"></app-student>
  </div>
Sign up to request clarification or add additional context in comments.

2 Comments

I second this as it supports the angular design methodology which is to mitigate DOM manipulation by properly templating as this answer demonstrates.
Ok, I overcomplicated this issue. Your approach is the way to go, thanks
1

I am not sure if its possible this way, but I did similar thing in other way

In template add

 <ng-template #target></ng-template>

In component code

@ViewChild("target", { read: ViewContainerRef }) target;

private createComponent(type: Type<{}>) {
    let compFactory = this.cfr.resolveComponentFactory(type);
    return this.target.createComponent(compFactory);
}

private init(){
  this.target.clear();
  //loop here 
  var component = this.createComponent(StudentDave);
  //here you can listen component.OnEvent.Subscribe 
  //Or even component.student = {name: "Olga", grade: 2};
}

But i think your question is a bit wrong basically you should have 1 StudentComponent which will accept @Input student; So you will always create same component but assign different inputs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.