Angular4父組件向子組件傳值

場景:由父組件輸入值可以傳到子組件

通過@Input傳值

先定義一個(gè)子組件

ng g component order

在order.component.ts里面定義
這里是Input要記得引入 import { Component, OnInit ,Input} from '@angular/core'

export class OrderComponent implements OnInit {
  @Input()   //一定要寫上@Input裝飾器
  stockCode:string;
  @Input()
  amout:number
  constructor() { }
  ngOnInit() {
  }
}

order.component.html輸入

<div>
  我是子組件
</div>
<div>
  買{{amout}}手{{stockCode}}股票
</div>

在父組件app.component.ts里面定義

export class AppComponent {
  stock = "";
}

在父組件的模板app.component.html里面定義

<div>
  我是父組件
</div>
<div>
  <input type="text" placeholder="請輸入股票代碼" [(ngModel)]="stock">
  <app-order [stockCode]="stock" [amout]="100"></app-order>
</div>

雙向數(shù)據(jù)綁定會報(bào)錯(cuò)# Angularjs2-Can't bind to 'ngModel' since it isn't a known property of 'input'.......
解決辦法是在app.module.ts的imports加入 FormsModule

官方文檔.png

最終效果.png

以上的例子只能通過父組件向子組件傳值

通過路由參數(shù)傳值

export class OrderComponent implements OnInit {
  @Input()
  stockCode:string;
  @Input()
  amout:number
  constructor(routeInfo: ActivatedRoute) { 
    setInterval(){
      this.stockCode = "Apple";
    },3000)
  }
  ngOnInit() {
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • # 1:@Input 步驟: 1:父組件調(diào)用子組建時(shí)傳方法 2:在子組件引入Input 3:在子組件聲明,通過In...
    __凌閱讀 772評論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評論 19 139
  • 第一節(jié):初識Angular-CLI第二節(jié):登錄組件的構(gòu)建第三節(jié):建立一個(gè)待辦事項(xiàng)應(yīng)用第四節(jié):進(jìn)化!模塊化你的應(yīng)用第...
    接灰的電子產(chǎn)品閱讀 13,782評論 64 25
  • # 1: @Input 步驟: 1:父組件調(diào)用子組建時(shí)傳入值/方法 2:在子組件引入Input模塊 3:在子組件聲...
    __凌閱讀 524評論 0 0
  • 組件基礎(chǔ) 組件用來包裝特定的功能,應(yīng)用程序的有序運(yùn)行依賴于組件之間的協(xié)同工作。組件是angular應(yīng)用的最小邏輯單...
    oWSQo閱讀 1,447評論 0 0

友情鏈接更多精彩內(nèi)容