简体   繁体   English

我可以将模板应用于Angular中ngFor-循环的对象变量吗?

[英]Can I apply a template to a object-variable of a ngFor - loop in Angular?

I have a app-projects template which is a list of ProjectComponent . 我有一个app-projects模板,它是ProjectComponent的列表。 For ProjectComponent . 对于ProjectComponent I have the app-project template. 我有应用程序项目模板。

<ul>
<li *ngFor="let project of projects">
  <app-project></app-project> 
</li>
</ul>

Component: 零件:

@Component({
  selector: 'app-project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.css']
})
export class ProjectComponent implements OnInit {

  constructor(title: string, description: string, questions: string[]) { }

  ngOnInit() {
  }

}

So, now I want to iterate over the the individual projectComponents while applying their templates. 因此,现在我想在应用其模板时遍历各个projectComponents。

But I could not figure out how to do that: If I want to stick with the separate template I somehow would have to pass the item to the template. 但是我不知道该怎么做:如果我要坚持使用单独的模板,则必须以某种方式将项目传递给模板。

I found that it would be possible for single properties via Inputs, but that does not help me much with this. 我发现通过输入可以使用单个属性,但这对我没有太大帮助。

First you need to get the project into your ProjectComponent as input property using @Input() to do that. 首先,您需要使用@Input()project作为输入属性进入ProjectComponent

You could use like bellow: 您可以像下面这样使用:

ProjectComponent: ProjectComponent:

export class ProjectComponent {

  @Input() project;

  constructor() { }

}

In the template you are using <app-project> you need to input that project property into ProjectComponent like bellow: 在您使用<app-project>的模板中,您需要将该project属性输入到ProjectComponent ,如下所示:

<ul>
    <li *ngFor="let project of projects">
        <app-project [project]=project></app-project>
    </li>
</ul>

WORKING DEMO 工作演示

Hope this will help you! 希望这个能对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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