使用angular一周,組件傳值和react不同,因此整理如下,以備后查!
@Input是angular提供給父元素傳遞信息的窗口,功能顧名思義——輸入值。
具體用法如下:
- 父組件
//parent.component.ts
import { Component, Input } from '@angular/core'
@Component({
selector: 'parent',
templateUrl: './parent.component.html'
})
export class ParentComponent {
parentData: {
data1:string = '測(cè)試字符串1'
}
}
//parent.component.html
<div>
<child [childData]="parentData"></child>
</div
在父組件上定義了parentData對(duì)象,在HTML文件中,包含了子組件<child />。這里需要介紹angular屬性綁定方法[屬性名],在方括號(hào)中加入屬性名比如src、href等,當(dāng)然可以自定義,比如這里的childData。這個(gè)地方相當(dāng)于將父組件要傳遞給子組件的對(duì)象parentData賦給子組件屬性childData。這樣子組件只要定義好@Input裝飾器就能拿到parentData對(duì)象。
- 子組件
//child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'child',
templateUrl: './child.component.html'
})
export class ChildComponent {
@Input() childData;
}
另外,Input 裝飾器支持一個(gè)可選的參數(shù),用來(lái)指定組件綁定屬性的名稱。如果沒有指定,則默認(rèn)使用 @Input 裝飾器,裝飾的屬性名。比如:
- 父組件
//parent.component.ts
import { Component, Input } from '@angular/core'
@Component({
selector: 'parent',
templateUrl: './parent.component.html'
})
export class ParentComponent {
parentData: {
data1:string = '測(cè)試字符串1'
}
}
//parent.component.html
<div>
//改了這里
<child [jianshu]="parentData"></child>
</div
- 子組件
//child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'child',
templateUrl: './child.component.html'
})
export class ChildComponent {
//命了個(gè)名
@Input('jianshu') childData;
}
the end!