输出

时间:2018-01-09 22:39:15

标签: angular angular-components

我是angular 2的新手,我一直在尝试获取父组件属性的值,该组件称为父组件的@output实现。这是代码

ParentPage.ts

export class ParentPage {
    name: string;

    constructor(){ this.name = "john doe"; }

    handleChild(text){ 
        console.log(this.name);
    }
}

ParentPage.html

<div child-component (childClick)="handleChild($event)"></div>

childComponent.ts

@Component( {
    selector: '[child-component]'
})
export class ChildComponent implements OnInit {

    @Output() childClick = new EventEmitter();

    constructor(){}

    ngOnInit(){
        this.childClick.emit('event emitted');
    }
}

问题是this.name未定义。我如何获得该属性的值。

2 个答案:

答案 0 :(得分:0)

当您从子组件发送事件时,您需要捕获该事件并从中获取(name)。

根据您的情况,您在constructor设置了价值。我想说在任何角度生命周期函数中设置name的值,如ngOnInit

ngOnInit() {
   this.name = "john doe";
}

handleChild(event: any){ 
    console.log(event.name);
}

答案 1 :(得分:0)

改变这个:

<div child-component (childClick)="handleChild($event)"></div>

到此:

<child-component (childClick)="handleChild()"></child-component>

由于您对根据评论将数据从子级传递到父级不感兴趣,请更改此:

this.childClick.emit('event emitted');

到此:

this.childClick.emit();