数据未从 child 组件 angular 传递到 parent 8

Data not being passed to parent from child component angular 8

我有一个 select 下拉菜单,它应该将 selected 字体 object 返回到 parent。但出于某种原因,我不明白为什么,键正在打印,但字体 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);
  }

}

然后在我的 parent 中,我这样做:

parent-component.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 参数的名称。您正在使用触发事件的 public 方法的名称。

我的父 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 方法。在子 public.

中创建@output

事件发射器名称基本上就是您尝试从子级输出到父级的方法。

<app-settings-font-selector (newFont)="getFontValue($event)" [fonts]="fonts"></app-settings-font-selector>

你的情况是 newFont。

示例:sample