[英]Data not being passed to parent from child component angular 8
我有一個 select 下拉列表,它應該將所選字體 object 傳遞回父級。 但由於某種原因,我不明白為什么,關鍵是打印,但字體 object 返回未定義。 它只是不想綁定。
.html
<app-settings-font-selector (newFont)="getFontValue($event)" [fonts]="fonts"></app-settings-font-selector>
<button class="update" (click)="updateFont('header_font', selectedFont)">Update Font</button>
.child-html
<li>
<select *ngIf="fonts" [(ngModel)]="selectedFont" (click)="selectFont(selectedFont)">
<option disabled hidden [value]="selectUndefinedOptionValue">Choose a New Font
</option>
<ng-container *ngFor="let font of fonts; let i = index;">
<option [ngValue]="font">{{ font.font_family }}</option>
</ng-container>
</select>
</li>
.child-component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Fonts } from '../fonts';
@Component({
selector: 'app-settings-font-selector',
templateUrl: './settings-font-selector.component.html',
styleUrls: ['./settings-font-selector.component.scss']
})
export class SettingsFontSelectorComponent implements OnInit {
@Input()
fonts: Fonts[];
selectedFont: Fonts;
@Output()
private newFont = new EventEmitter<Fonts>();
constructor() { }
ngOnInit() {
}
public selectFont() {
const selectedFont = this.selectedFont
this.newFont.emit(selectedFont);
}
}
然后在我的父母中,我正在這樣做:
父組件.ts
selectedFont: Fonts;
public getFontValue(selectedFont: Fonts){
if(selectedFont){
this.selectedFont = selectedFont;
}
}
updateFont(key: string){
console.log(key, this.selectedFont);
}
我似乎無法理解為什么該變量沒有綁定。 誰能看到我在這里做錯了什么?
eventEmitter 是您必須包含在自定義 html 選擇器app-settings-font-selector
中作為參考的元素。 在你的情況下:
(newFont)="getFontValue($event)"
在綁定中,您必須使用@Output 參數的名稱。 您正在使用觸發事件的公共方法的名稱。
我的父 HTML 綁定應該是newFont
而不是selectFont
。 以下代碼應該可以工作:
父 html:
<app-settings-font-selector (newFont)="getFontValue($event)" [fonts]="fonts"></app-settings-font-selector>
<button class="update" (click)="updateFont('header_font', selectedFont)">Update Font</button>
更新:還嘗試將console.log
移動到父級的getFontValue
方法。 將子項中的@output 設為公開。
事件發射器名稱基本上是您嘗試從子級到父級的 output 的方法。
<app-settings-font-selector (newFont)="getFontValue($event)" [fonts]="fonts"></app-settings-font-selector>
在你的情況下是newFont。
示例:樣本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.