简体   繁体   English

Angular2嵌套组件变量无法在模板中访问

[英]Angular2 nested components variables not accessible in template

Iv'e recently started playing around with Angular2, and face a pretty basic issue. Iv'e最近开始使用Angular2,并且遇到了一个非常基本的问题。

I'm trying to create a simple parent component that is simply a container of dynamic boxes. 我正在尝试创建一个简单的父组件,该组件只是一个动态框的容器。 Each box has it's own properties and data. 每个框都有其自己的属性和数据。

What Iv'e done so far is the following: 到目前为止,我所做的是:

The container class: 容器类:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {IONIC_DIRECTIVES} from 'ionic-angular';
import {MainBox} from './../../component/main-box/main-box.component';

@Component({
  selector      :   'wrapper',
  templateUrl   :   'build/component/main-container/main-container.component.html',
  directives    :   [IONIC_DIRECTIVES, MainBox]
})

export class MainContainer {
  boxes : MainBox[] = [
    {title : "mor"},
    {title : "naama"}
  ];
  constructor() {

  }
}

The container template 容器模板

<div>
    <main-box *ngFor="let box of boxes"></main-box>
</div>

** main-box stands for each individual box **主箱代表每个单独的箱子

MainBox class: MainBox类别:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {IONIC_DIRECTIVES} from 'ionic-angular';

@Component({
  selector      :   'main-box',
  templateUrl   :   'build/component/main-box/main-box.component.html',
  directives    :   [IONIC_DIRECTIVES]
})

export class MainBox {
  title:any;
  constructor() {
  }
}

Box Template 框模板

{{title}}

I would expect that Angular will automatically display the right title, but in fact it shows nothing. 我希望Angular会自动显示正确的标题,但实际上它什么也不显示。

On the other hand, if I do the following: 另一方面,如果我执行以下操作:

<div *ngFor="let box of boxes">{{box.title}}</div>

I can see the title just fine, but it's not good enough for me since I wish to completely separate the template files. 我可以看到标题很好,但是对我来说还不够好,因为我希望完全分离模板文件。

Thanks! 谢谢!

You need to pass data explicitly to children: 您需要将数据显式传递给子代:

<div>
    <main-box *ngFor="let box of boxes" [title]="box.title"></main-box>
</div>
export class MainBox {
  @Input()title:any;
  constructor() {
  }
}

You can only access the title in the main box if you provide the title as an input to it 如果您提供标题作为输入,则只能在主框中访问标题

   <div *ngFor="let box of boxes">
             <main-box [title]="box.title"></main-box>
   </div>

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

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