ngFor not able to iterate in another component through component binding with @Input

134 Views Asked by At

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  serverElements :[{type:"blueprint",name:"abnc",content:'Just A Test'}];

}

app.component.html

<div class="container">
 

  <div class="row">
    <div class="col-xs-12">
      <app-server-element *ngFor="let serverElement of serverElements" [childElement]="serverElement">abc</app-server-element>
    </div>
  </div>
</div>

src-->app-->server-element

server-element.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-server-element',
  templateUrl: './server-element.component.html',
  styleUrls: ['./server-element.component.css']
})
export class ServerElementComponent implements OnInit {
 @Input('childElement') element:{type:string,name:string,content:string};

 constructor() { }

  ngOnInit(): void {
  }

}

server-element.component.html

<div class="panel panel-default">
  <div class="panel-heading">Hello</div>
  <div class="panel-body">
    <p>
      <strong *ngIf="element.type ==='server' " style="color: red;"> {{ element.content }}</strong>
      <em *ngIf="element.type==='blueprint'"> {{element.content}} </em>
    </p>
  </div>
</div>

it should iterate single serverElements by <app-server-element *ngFor> . But it isnt doing ,although the course which i am folowing(Maximilian Schwarzmuller) code works fine .. Help

1

There are 1 best solutions below

0
Abhinav Kumar On

you missed the assignment of serverElements. It should have some value, you just declare the type.

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // assign the value, you declare it as type but it was emplty
  serverElements = [
    { type: "blueprint", name: "abnc", content: "Just A Test" }
  ];

}