【问题标题】:Sharing Data Between Angular 7 Components在 Angular 7 组件之间共享数据
【发布时间】:2020-03-14 05:00:03
【问题描述】:

我想将来自child-information 组件的age 输入的数据发送到包含垂直线的组件age-line。当它到达年龄时,这条线向左移动'age * 100 pixels'

我的代码有什么问题?没有错误消息。

Child-inf.html:

 <button id="okButton" (click)=addAge()>OK</button>
 Age : <input 
 type="text" name="Age" value="Kor" id="ageId" onfocus="this.value = 
 this.value=='Kor'?'':this.value;" onblur="this.value = 
 this.value==''?'Kor':this.value;">

子-inf.ts:

export class ChildInformationsComponent implements OnInit {
 age:number = 1;
  @Output() buttonClicked: EventEmitter<number> = new EventEmitter<number>();
  constructor(private el: ElementRef) { }

  ngOnInit() { }

  addAge(){
    this.age =parseInt((<HTMLInputElement>document.getElementById('ageId')).value);
    this.buttonClicked.emit(this.age); 
  }
}

年龄线html:

 <div class="age-line" [style.left.px]="age * 100"> <div class="line"></div> </div>

年龄线 ts:

export class AgeLineComponent implements OnInit {

 constructor() { }
 age: number= 1;


 showNextComponent(emittedAge: number) {
   this.age = emittedAge;
   console.log('Button clicked');
 }

 ngOnInit() { }

}

【问题讨论】:

  • 年龄行没有属性(buttonClicked),它存在于Child-inf
  • 发布包含年龄线和子选择器的父 html
  • bro 0 * n = 0. 所以初始化 age: number = 1
  • 还是不行:(

标签: css angular output eventemitter pass-data


【解决方案1】:

您似乎缺少 Age Line HTML

中的子组件

您的输出按钮已单击,因此您的代码需要看起来像这样。

年龄线 HTML:

<div class="age-line" [style.left.px]="age * 100"> <div class="line"></div> </div>
<child-inf (buttonClicked)="showNextComponent($event)"></child-inf>

现在,当您发出 buttonClicked 时,showNextComponent 方法将触发。

您还应该从 AgeLine.ts 扩展 Child-inf.ts

export class ChildInformationsComponent extends AgeLineComponent{
    // Methods and stuff
}

【讨论】:

    【解决方案2】:

    在 Angular 中,当您需要在子-父关系中从子组件向其父级发出值时,您可以使用 Output()

    我没有看到 Age line 组件作为子组件具有 Child-inf

    如果您希望Child-infAge line 具有子父关系,则应在Age line Html 中包含Child-inf

    年龄线 html:

    <div class="age-line" [style.left.px]="age * 100"> <div class="line"></div> </div>
    <child-inf></child-inf>
    

    这里我假设Child-inf组件选择器是:child-inf

    那么如果你想在Child-inf 组件中监听输出事件,在Age line html 中你必须这样做:

    年龄线 html:

    <div class="age-line" [style.left.px]="age * 100"> <div class="line"></div> </div>
    <child-inf (buttonClicked)="showNextComponent($event)"></child-inf>
    

    【讨论】:

    • 好的。让我们看看:Age : &lt;input (buttonClicked)='showNextComponent($event)' 为什么在 child-inf 的输入中有 (buttonClicked)?你不应该请删除它。另外,您是否尝试查看 addAge la 是否被触发以及是否看到输入的值?
    • 在您的建议下,我当然从年龄输入中删除了 buttonClicked,但仍然无法正常工作:(
    • 我希望您可以将代码或部分代码上传到stackblitz.com,因为在这种情况下,看到此问题的所有用户都会看到当前问题以及我们遇到的解决方案
    • 太好了,只有一条评论,你忘了添加app.module
    • 完成,如果没问题请告诉我
    猜你喜欢
    • 2023-03-10
    • 2019-08-04
    • 2018-09-27
    • 2018-10-12
    • 2019-08-05
    • 2018-02-17
    • 2021-01-04
    • 2019-01-22
    相关资源
    最近更新 更多