我試圖從具有與子組件關聯的(更改)事件的選擇輸入向父元素傳遞輸入值。 希望變量在每次更新子組件變量時都得到更新。當變量基於使用Angular的更改事件更改時,將變量從子組件傳遞到父組件
我的問題與Question不同,因爲我在變化事件上發生了變化,每次變量變化時都需要更新。
我能夠使用ViewChild和AfterViewInit解決這個問題,但在控制檯中出現錯誤:ExpressionChangedAfterItHasBeenCheckedError:檢查後表達式已更改。先前的值:'未定義'。當前值:'測試'。
想象一下,這樣做有一個簡單的方法。請記住,我對Angular仍然很陌生。
輔元件模板:
<form>
<div class="form-group">
<label for="Master-Products">Select Master Product</label>
<select [(ngModel)]="selectedValue" name="pow" (change)="pow = $event.target.value; onKeyUp()" class="form-control" id="Master-Products">
<option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
</select>
</div>
</form>
兒童成分:
export class MasterInputComponent {
powers: any[] = [ 'power1', 'power2', 'power3' ];
submitted = false;
pow:string = 'Testing';
selectedValue = null;
constructor() { }
onKeyUp(value): void{
console.log('Value: ',this.pow);
}
家長組件的模板:
<div role="tabpanel" class="tab-pane" id="accessories">
<h1>ACCESSORIES</h1>
<h4>Testing: {{power}}</h4>
<master-input (change)="recieveMessage($event.target.value)"></master-input>
<accessories></accessories>
家長組件:
export class AppComponent implements AfterViewInit{
@ViewChild(MasterInputComponent) child;
title = 'Having FUN with Angular';
posts: any[];
power:string;
constructor(private service:ProductsService){}
ngAfterViewInit(){
this.power = this.child.pow;
}
recieveMessage(value){
console.log('Event: ',value);
this.power = value;
console.log('Favorite has changed')
}
任何幫助將不勝感激,謝謝!
在這種情況下,你會希望'輸出'和一個EventEmitter :) https://angular.io/guide/component-interaction#parent-listens-for-child-event – Alex
[將數據從孩子傳遞給父組件Angular2](https://stackoverflow.com/questions/42107167/pass-data-from-child-to-parent-component-angular2) – Alex
我試過這之前我目前的解決方案,我也有一個錯誤。我不記得這個錯誤。這兩種方式的工作,但我仍然最終在控制檯中的錯誤。你介意給我舉個例子嗎?你的方式很可能與我實施它的方式不同。 –