angular4.0 父子组建之间的相互通信

  • 父组建---->子组建 传递信息

  • 首先先通过angular脚手架生成两个基本组件,有一个好处是

    会自动关联到跟模版,节约时间,而且还是偷懒

  • ng generate component component-name 这句话有简写的方式,可以自己去搜

  • demo如下

    //father.component.ts
    @Component({
    selector: 'app-component-father',
    template:`
    <son [title]="'这是父组件定义的数据标题'"></son>
    `,
     })
    export class ComponentFatherComponent {
    }
    //
    import { Component, Input } from '@angular/core';

    @Component({
    selector: 'son',
    template:`
        <h1>{{ title }}</h1>
    `,
    styleUrls: ['./component-son.component.css']
    })
    export class ComponentSonComponent{
    @Input() title: string;
    }
  • 我们来看看,这倒底是神马一回事儿,第一次听到组件通讯

    顿时觉得高大上,理清思路之后,这简直弱爆了,就是属性绑定

  • 首先在子组建 需要引入输出接口 ---就是这个一个玩意,多了一个input,

    表示输入的意思,可以叫什么装饰器属性

    import { Component, Input } from '@angular/core';
  • 把这玩意塞到 你在类里面定义的属性前--像这样
    @Input() title: string;
  • 在模版里面使用插值表达式输出title---由于没有赋值,所以是没有结果的结果

    这时候这倒父组件发挥作用---请看下面

    @Component({
    selector: 'app-component-father',
    template:`
    <son [title]="'这是父组件定义的数据标题'"></son>
    `,
     })
    export class ComponentFatherComponent {
    }

  • 干干净净的父组建什么东西都没有
    [title]="'这是父组件定义的数据标题'"
  • 就是东西 等号左边是 被绑定的属性 ,也就是子组建需要的东西的名字,

    等号右边就是你想输入的东西,你输什么鬼,页面就显示什么鬼

  • 饶了半天其实就是一个属性绑定的过程----说实话官网的那些文档只能看代码

  • 子组建----〉父组件 的有时间 再说