簡體   English   中英

Angular2嵌套組件變量無法在模板中訪問

[英]Angular2 nested components variables not accessible in template

Iv'e最近開始使用Angular2,並且遇到了一個非常基本的問題。

我正在嘗試創建一個簡單的父組件,該組件只是一個動態框的容器。 每個框都有其自己的屬性和數據。

到目前為止,我所做的是:

容器類:

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() {

  }
}

容器模板

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

**主箱代表每個單獨的箱子

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() {
  }
}

框模板

{{title}}

我希望Angular會自動顯示正確的標題,但實際上它什么也不顯示。

另一方面,如果我執行以下操作:

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

我可以看到標題很好,但是對我來說還不夠好,因為我希望完全分離模板文件。

謝謝!

您需要將數據顯式傳遞給子代:

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

如果您提供標題作為輸入,則只能在主框中訪問標題

   <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