首页 > 解决方案 > 在 Angular 7 组件之间共享数据

问题描述

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

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

儿童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;">

Child-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() { }

}

标签: cssangularoutputeventemitterpass-data

解决方案


在 Angular 中,当您需要在 Child-Parent 关系中将值从子组件发送到其父组件时,您可以使用Output() 。

我没有看到Age lineComponent 小时候有Child-inf.

如果你想要那个Child-inf并且Age line有一个子父关系,你应该Child-infAge lineHtml.xml 中包含它。

年龄线html:

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

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

然后如果你想在Child-infComponent 中监听 Output Event,在 Age linehtml 中你必须这样做:

年龄线html:

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

推荐阅读