繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM