angular@Input用法

使用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!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 組件基礎(chǔ) 組件用來(lái)包裝特定的功能,應(yīng)用程序的有序運(yùn)行依賴于組件之間的協(xié)同工作。組件是angular應(yīng)用的最小邏輯單...
    oWSQo閱讀 1,446評(píng)論 0 0
  • 單向從數(shù)據(jù)源到視圖 單向從視圖到數(shù)據(jù)源 雙向 DOM property 的值可以改變;HTML attribute...
    chrisghb閱讀 1,001評(píng)論 1 1
  • 學(xué)習(xí)資料來(lái)自 Angular.cn 與 Angular.io。 模板語(yǔ)法 在線例子 在 Angular 中,組件扮...
    小鐳Ra閱讀 3,976評(píng)論 0 3
  • 裝飾器的作用就是在添加裝飾器的地方在不改動(dòng)原有代碼的情況下增加額外的功能。Angular框架中裝飾器是一個(gè)函...
    tuacy閱讀 2,560評(píng)論 0 2
  • 一.課程簡(jiǎn)介 (注意:這里的AngularJS指的是2.0以下的版本) AngularJS的優(yōu)點(diǎn): 模板功能強(qiáng)大豐...
    壹點(diǎn)微塵閱讀 1,005評(píng)論 0 0

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