如何将一个组件值打印到另一个组件

时间:2018-04-24 09:53:19

标签: angular angular2-routing angular2-forms angular2-services angular2-directives

amountcomponent.ts

import { Component,Input,OnInit} from '@angular/core';
@Component({
    selector: 'appchild',
    templateUrl: './amountcomponent.component.html'


})
export class AmountComponent implements OnInit{

    @Input() greetMessage: string ;


    onKey(event: any) {
        console.log(event.target.value)

    }
    ngOnInit(){

    }    
}

dobcomponent.component.ts

    import { Component } from "@angular/core";
    import {AmountComponent} from "./amountcomponent.component";

    @Component({

        templateUrl: './dobcomponent.component.html'

    })

    export class DoBComponent {        
        public quantity:any;            
        childmessage : string = "I am passed from Parent to child component"        
        onquantity(event: any) {
            this.quantity = event.target.value
            console.log(this.quantity)        
        }
       }

这里我提到了我的amountcomponent和dobcomponent我不知道从Dob.Component.ts访问this.quantity到amountcomponent.ts。

我已经提到过amountcomponent和dobcomponent

的Html代码

amountcomponent.html

<input (keyup)="onKey($event)">
<h2>{{dob.date}}</h2>

dobcomponent.html

<input (keyup)="onquantity($event)">

1 个答案:

答案 0 :(得分:0)

如果组件彼此相邻,您可以创建一个引用变量并将其输入到amountcomponent

<div>
  <amount [dob]="dob"></amount>
  <dob #dob></dob>
</div>
在AmountComponent中:

@Input('dob') dobComponent: DobComponent;