Angular組件間傳值

在Angular中,父組件調用子組件,可以傳遞參數,子組件根據傳遞過來的參數返回相應的數據;

父組件向子組件傳參,過程如下:

方法一:

在子組件中:

@Component({
selector: 'test-component',
template: `{{inputValue}}`,
inputs: ['inputsValue'] 
})
export class TestComponent {
private inputsValue;//注意,要在組建內聲明,才能使用
}

在父組件中:

@Component({
selector: 'parent-component',
template: `<test-component [inputsValue]="data"></test-component>`//以“[屬性]=值”的方式傳遞
})
export class ParentComponent {
  private data = 'Hello InputValue~!';
}

如果不配置元數據,我們還可以在組件類中用“@Inputs() inputsValue”聲明,效果一樣。

方法二:

在子組件中:

import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'test-component',
template: `{{inputValue}}`
})
export class TestComponent {
@Input() name: string;//注意,要在組建內聲明,才能使用
}

在父組件中設置與方法一相同,此處不再贅述。

PS:@Input後面要加上(),不然沒效果。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章