angular6組件傳值 - set及get

參考:blog.csdn.net/kuangshp128…javascript

一. angular6 組件之間傳值的幾種方式:

  • 父組件經過屬性綁定到子組件,子組件經過事件傳遞參數到父組件
  • 父組件經過局部變量獲取子組件的引用
  • 父組件使用@ViewChild獲取子組件的引用
  • 兩個不相關聯的組件使用中間人模式交互
  • 終極大招:建立一個服務注入到組件中
  • 直接把父組件當作服務注入到子組件中

二. setget方法 :父組件傳遞數據到子組件,子組件接受數據,對其接收的數據進行處理再顯示

// 父組件 ts
data:string = "parent";  // 傳遞一個parent給子組件

// 父組件 html
<app-comdemo01 [input]="data"></app-comdemo01> 複製代碼
//子組件ts文件
export class Comdemo01Component implements OnInit {
  _input: string;
  @Input()
  public set input(v: string) {
    this._input = v.toUpperCase();  //轉換大寫輸出
  }
  public get input(): string {
    return this._input;
  }
  constructor() {
  }
  ngOnInit() {
  }
}

//子組件html代碼
I am fron {{input}}
複製代碼
相關文章
相關標籤/搜索