数据未从子组件angular 8传递给父级

时间:2019-09-19 13:07:33

标签: angular parent-child

我有一个select下拉菜单,该下拉菜单应将选定的字体对象传递回父对象。但是由于某种原因,我不明白为什么,关键是打印,但是字体对象返回未定义。它只是不想绑定。

.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-component.ts

selectedFont: Fonts;

public getFontValue(selectedFont: Fonts){
  if(selectedFont){
    this.selectedFont = selectedFont;
  }
}

updateFont(key: string){
  console.log(key, this.selectedFont);
}

我似乎无法理解为什么变量没有绑定。有人可以在这里看到我在做什么错吗?

3 个答案:

答案 0 :(得分:0)

eventEmitter是您必须包含在自定义html选择器app-settings-font-selector中作为参考的元素。就您而言:

(newFont)="getFontValue($event)"

答案 1 :(得分:0)

在绑定中,必须使用@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公开。

答案 2 :(得分:0)

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

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

在您的情况下为newFont。

示例:sample