如何获取ngFor listofLog Angular中的值

问题描述 投票:0回答:2

我是Angular的新手,所以我需要在一个带有ngFor的组件中将值传递给另一个。假设有两个组件:日志和日志。我的logs.component.html是:

//iterane on a list that I have created 
    <app-log *ngFor="let log of listLog;let i= index"></app-log>

在我的log.component.html中:

//Something like this
<p>The server timestamp {{ log[i] }}</p>

如何在log.component.html中传递日志值以及我如何打印它?

angular ngfor
2个回答
4
投票

你可以做这样的事情。

家长component.html

<ng-container *ngFor="let log of listLog">
  <app-log [log]="log"></app-log>
</ng-container>

APP-log.ts

@Component({
  selector: 'app-log',
  styleUrls: ['./app-log.component.scss'],
  templateUrl: './app-log.component.html'
})

export class LogComponent {

  @Input()
  public log: any; // change any to the data type of log

}

APP-log.html

<div>
  {{log}}
</div>

0
投票

我想你试着这样做:

父组件:

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

import { HEROES } from './hero';

@Component({
  selector: 'app-hero-parent',
  template: `
    <h2>{{master}} controls {{heroes.length}} heroes</h2>
    <app-hero-child *ngFor="let hero of heroes"
      [hero]="hero"
      [master]="master">
    </app-hero-child>
  `
})
export class HeroParentComponent {
  heroes = HEROES;
  master = 'Master';
}

子组件:

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

import { Hero } from './hero';

@Component({
  selector: 'app-hero-child',
  template: `
    <h3>{{hero.name}} says:</h3>
    <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
  `
})
export class HeroChildComponent {
  @Input() hero: Hero;
  @Input('master') masterName: string;
}

你在这里有关于Angular文档的所有解释:https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding

© www.soinside.com 2019 - 2024. All rights reserved.