简体   繁体   中英

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

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

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" }
  ];

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM