![](/img/trans.png)
[英]Component variable change not updated in view until mouseover in Angular 2
[英]Angular service variable change and updated another component
服務
clicked: string = '';
clickEvent(item){
this.clicked = ( this.clicked.length > 0 && this.clicked == item ) ? '' : item;
}
父組件
constructor(private qqs: qqService) {}
clicked = this.qqs.clicked;
parent.html
<app-child [clicked]="clicked"></app-ou>
子組件
constructor(private qqs: qqService) {}
@Input() clicked;
click(item){
this.qqs.clickEvent(item);
}
child.html
<div class="a" (click)="click('some string')"></div>
如果用戶單擊child.html
child.component click()將起作用並將一些字符串傳遞給服務
服務將更改點擊的變量
比父母 組件從服務獲取新變量
並通過@Input()傳遞給所有孩子
現在我的問題是父母。 組件無法從服務獲取新變量
如何解決?
child component
公開一個EventEmitter
屬性,當發生某些emits events
時,該屬性將emits events
。
父級綁定到該事件屬性並對這些事件做出反應。
子項的EventEmitter
屬性是一個輸出屬性,通常在此ParentComponent
看到@Output
裝飾
以下是代碼:
父組件
constructor(private qqs: qqService) {}
onClicked(item) {
console.log(item)
}
parent.html
<app-child [clicked]="clicked" (onclicked)="onClicked($event)"></app-ou>
子組件
import { Component, EventEmitter, Input, Output } from '@angular/core';
constructor(private qqs: qqService) {}
@Input() clicked;
@Output() onclicked = new EventEmitter<any>();
click(item){
this.clicked.emit(agreed);
}
child.html
<div class="a" (click)="click('some string')"></div>
您的代碼存在以下問題:
clickEvent
它都會更改clicked
引用。 clicked
保存了qqs.clicked
引用(假設代碼中的clicked
引用了this.clicked
),但是每當下次調用clickEvent
時, clickEvent
的引用將被更改,並且內部qqs.clicked
也將被clicked
有舊的參考。 解決方法是,暴露整個qqs
通過使它在parent.component公眾和parent.html替換到模板[clicked]="clicked"
到[clicked]="qqs.clicked"
。
這將解決您的問題,但我指出了幾件事:
<app-child [clicked]="clicked"></app-ou>
開始標記與結束標記不匹配。 clicked
價值需要什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.