Angular里的消息(Message)显示
使用命名行創(chuàng)建一個(gè)Angular Component:
ng generate component messages
創(chuàng)建一個(gè)message service:
ng generate service message
message service的實(shí)現(xiàn):其實(shí)就是內(nèi)部維護(hù)了一個(gè)字符串?dāng)?shù)組,存儲(chǔ)其他Component添加的message:
通過(guò)構(gòu)造函數(shù)參數(shù)注入的方式將message service注入到hero service中:
在hero Service里消費(fèi)message Service:
需要在message Component里顯示message Service內(nèi)部維護(hù)的字符串?dāng)?shù)組:
注意,此處11行的messageService必須定義成public,因?yàn)樾枰贑omponent view的html里使用它。
The messageService property must be public because you’re going to bind to it in the template.
Angular only binds to public component properties.
message Component的實(shí)現(xiàn):
<div *ngIf="messageService.messages.length"><h2>Messages</h2><button class="clear"(click)="messageService.clear()">clear</button><div *ngFor='let message of messageService.messages'> {{message}} </div></div>最后的效果:
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的Angular里的消息(Message)显示的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 三星一季度手机出货量为6000万部 预计
- 下一篇: 马斯克疯狂降价!特斯拉Model Y已比