簡體   English   中英

使用@Input裝飾器從角度組件外部傳遞數據

[英]Using @Input decorator to pass data from outside the angular component

在離子應用程序中,我使用角度組件。 在該角度組件中,我有一個變量headerText ,它從使用該組件的頁面初始化。

問題是headerText變量總是未定義的。

我該如何解決這個問題?

這是定義headerText變量的角度組件。

import { Component, Input, OnInit } from '@angular/core';
import { MenuController, NavController } from 'ionic-angular';

@Component({
  selector: 'custom-header-text',
  templateUrl: 'custom-header-text.html'
})
export class CustomHeaderTextComponent implements OnInit {

  @Input() headerText: string;

  constructor(private navCtrl :  NavController,
              private menuCtrl : MenuController) {

  }

  ngOnInit() {
    setTimeout(() => {
      console.log('text = ' + this.headerText);
    }, 3000);
  }

  goBack() {
    this.navCtrl.pop();
  }

  openMenuPage() {
    this.menuCtrl.enable(true,'bl-menu')
    this.menuCtrl.open();
  }
}

這是我如何將值傳遞給此headerText變量使用此組件的位置。

<custom-header-text [headerText]="'Inbox'"></custom-header-text>

見下文。

這不起作用的原因是您放置<custom-header-text [headerText]="'Inbox'"></custom-header-text>的根元素不是角度組件。 因此,Angular不會編譯此元素。 Angular不會在運行時讀取屬性值,只是在編譯期間,否則我們會受到性能影響。

這里回答

根指令上的Angular 2輸入參數

您的代碼無法正常工作,因為未正確配置HeaderModule。

您的實施存在一些問題:

  1. 未在AppModule中正確設置Header模塊的路徑。
  2. HeaderComponent模板的路徑也未設置為正確的HTML文件。

修好后,它按預期工作。 這是你的ref的更新StackBlitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM