组件传值 - @input - output

  1. 输入属性@Input 装饰器 :当它通过属性绑定的形式被绑定时,值会“流入”这个属性
  2. 输出属性 @Output 装饰器:这个属性总是返回 EventEmitter 。 当它通过事件绑定的形式被绑定时,值会“流出”这个属性。
  3. 输入属性 @Input 通常接收数据值。 输出属性 @Output 暴露事件生产者,如 EventEmitter 对象。
  4. 参考链接:https://www.cnblogs.com/yw0219/p/7768960.html
一. 父组件给子组件传值 @input()
  1. 父组件 father.component.ts 提供数据
// 1. ------------ 父组件 father.component.ts 提供数据 ------------
import {Component} from "@angular/core";
@Component({
    selector: "my-father",
    templateUrl: "father.html"
})
export class FatherComponent {
    data: Array<Object>;
    constructor() {
        this.data = [
            { "id": 1,"name": "html" },
            { "id": 2, "name": "css" }]
    }
}

// ------------ 父组件 father.html ---------- 
<my-child [info]="data"></my-child>    // 引用子组件, 并使用属性传递数据过去
  1. 子组件 child.component.ts 获取数据
// ------------ 父组件 father.component.ts 提供数据 ------------
import {Component, Input} from "@angular/core";
@Component({
    selector: "my-child",
    templateUrl: "child.html"
})
export class ChildComponent {   
    // 使用@Input获取传递过来的数据
    @Input()
    info: Array<Object>;
    constructor() {
    }
}
// ------------------- 子组件 child.html --------------------
<ul>
    <li *ngFor="let item of info">  
        {{item.name}}
    </li>
</ul>
二. 子组件向父组件 emit 传值 @Output()
  1. 子组件 three-link.component.ts emit提供数据
import {Output, EventEmitter} from "@angular/core";

// 1. 定义输出变量
export class ThreeLinkComponent {
    province: string;
    @Output() provinceOut = new EventEmitter();       // 输出参数
    constructor() {
        this.province = "陕西";
    } 
}

// 2. 事件发出,发射变量给父组件
provinceChange() {
    this.provinceOut.emit(this.province);
}
  1. 父组件 接收数据
// 函数接受子函数传递过来的变量, 子函数中emit的时候触发这个函数。
<three-link (provinceOut)="recPro($event)"></three-link>   // 父组件模板接收数据

recPro(event) {
   this.province = event;
}
三. 综合:通过 输入属性@Input() 以及 输出属性 @Output() 进行组件间传值
// 父组件 html 
<li *ngFor="let item of dataSet;let i = index">
    <span>{{item.name}}</span> {{i+1}}--{{item.id}}
    <app-child [names]="item" (foo)="bar($event)"></app-child>   // 父组件传递属性【names】,接收事件(foo)
</li>
// 父组件 ts
dataSet = [
    {"id":0,"name":"张三"},
    {"id":1,"name":"李四"},
    {"id":2,"name":"王五"},
]
bar(event:any){  // 接收子组件发射的事件
    console.log(event);
}
// 子组件 html
<input type="button" value="{{names.name}}" (click)="todo($event)"/>
// 子组件 ts
export class ChildComponent implements OnInit {
  @Input() names:any = {} 	//接收父子间传递的值
  @Output() foo = new EventEmitter<string>()    //子组件发射事件给父组件
    this.foo.emit('你好');
  }
  constructor() { }
  ngOnInit() {
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值