Angular元件之間的互動

2021-10-10 19:45:26 字數 3663 閱讀 4390

通過輸入型繫結把資料從父元件傳到子元件

child.component.ts

export

class

childcomponent

implements

oninit

ngoninit()

:void

}

child.component.html

style

="background-color

: #749f84

">

>

child works!p

>

>

} says:h3

>

>

i, }, am at your service, }.p

>

div>

parent.component.ts

export

class

parentcomponent

implements

oninit

master =

'master'

constructor()

ngoninit()

:void

}

parent.component.html

[hero]

="hero"

[master]

="master"

>

>

父元件監聽子元件的事件

child.component.ts

export

class

childcomponent

implements

oninit

constructor()

ngoninit()

:void

}

child.component.html

>

}h4>

(click)

="vote(true)"

[disabled]

="didvote"

>

agreebutton

>

(click)

="vote(false)"

[disabled]

="didvote"

>

disagreebutton

>

parent.component.ts

export

class

parentcomponent

implements

oninit

constructor()

ngoninit()

:void

}

parent.component.html

>

should mankind colonize the universe?h2

>

>

agree: }, disagree: }h3

>

*ngfor

="let voter of voters"

[name]

="voter"

(voted)

="onvoted($event)"

>

>

父元件與子元件通過本地變數互動

父元件不能使用資料繫結來讀取子元件的屬性或呼叫子元件的方法。但可以在父元件模板裡,新建乙個本地變數來代表子元件,然後利用這個變數來讀取子元件的屬性和呼叫子元件的方法,如下例所示。

子元件countdowntimercomponent進行倒計時,歸零時發射乙個飛彈。startstop方法負責控制時鐘並在模板裡顯示倒計時的狀態資訊。

父元件呼叫*@viewchild()*

這個本地變數方法是個簡單便利的方法。但是它也有侷限性,因為父元件-子元件的連線必須全部在父元件的模板中進行。父元件本身的**對子元件沒有訪問權。

如果父元件的類需要讀取子元件的屬性值或呼叫子元件的方法,就不能使用本地變數方法。

當父元件類需要這種訪問時,可以把子元件作為 viewchild,***注入***到父元件裡面。

countdown-parent.component.ts

import

from

'@angular/core'

import

from

'../child/child.component'

@component(}

`,})

export

class

countdownparentcomponent

implements

afterviewinit

ngafterviewinit()

,0)}

start()

stop()

}專案例項:alan-desk index模組中header和sidebar互動

Angular元件之間常用互動方法

1.通過輸入型繫結把資料從父元件傳到子元件 child.component.ts export class childcomponent implements oninit ngoninit void child.component.html style background color 749f8...

angular子父元件之間的互動

子元件傳遞的是乙個字串,可以根據相應的需求定義成如數字,陣列,物件等型別。import from angular core output private childouter new eventemitter output private childouter2 new eventemitter s...

angular 元件互動

angular是以元件化的形式來實現,因而元件互動是極為基礎且重要的,下面對其元件之間的互動方式一一介紹。1.通過輸入型繫結把資料從父元件傳到子元件。3.父元件監聽子元件的事件 4.父元件與子元件通過本地變數互動 注 用本地變數可使用在父元件模板裡面來讀取子元件的屬性或者使用其方法 5.父元件呼叫 ...