Angular系列学习三:父子组件之间的交互(常见的组件通讯场景)

作者:心叶
时间:2018-07-24 16:48:56

通过输入型绑定把数据从父组件传到子组件

通过@Input()可以实现父组件传递数据给子组件,下面先看看子组件代码:

import { Component, Input } from '@angular/core';
            
@Component({

    selector: 'child-comp',

    template: `
        
{{title}}

{{message}}

` }) export class ChildComponent { @Input() title: string; @Input('msg') message: string; }

其中@Input('msg')是为message定义了别名,接着,在父组件中通过属性就可以传递值进来了:



父组件通过监听子组件的事件获取子组件传递的数据

子组件传递数据给父组件是通过emit的方式,先看一下子组件代码:

import { Component, Input, Output, EventEmitter } from '@angular/core';
                
@Component({

    selector: 'child-comp',

    template: ''

})
export class ChildComponent {

    @Output() onDoit = new EventEmitter();
                
    doit(info: string) {

        this.onDoit.emit(info);

    }
}

通过@Output()触发父组件里面定义的onDoit事件,因此,需要在父组件中注册事件处理方法:


getInfo是定义的一个方法,$event就是子组件传递的数据,点击子组件的按钮就会触发这个方法(弹出一句话),方法代码如下:

......
    
    getInfo(info:string){
        alert(info);
    }

......  

你可能感兴趣的:(typescript,angular,webpack)