angular2 ng2 @input和@output理解及示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

angular2 ng2 @input和@output理解及示例

zxc19890923   2020-05-16 我要评论

angular2 @input和@output理解

先做个比方,然后奉上代码

比如:

<talk-cmp [talk]="someExp" (rate)="eventHandler($event.rating)">

input, [talk]="someExp" 这个标签可以理解为一个专门的监听器,监听父组件传递过来的someExp参数,并存入自身组件的talk变;好像是开了个后门,允许且只允许父组件的someExp进入,一旦进入立刻抓进一个叫talk的牢房,然后子组件中就可以通过@Input来定义这个变量talk然后使用它。

output ,(click)="eventHandler($event.rating) 这个意思是, 当子组件的click事件被触发,就执行父组件的eventHandler函数,并把子组件的参数$event.rating传递给父组件的eventHandler函数;就好像,当小孩子一哭(执行click事件),他的母亲立刻把他抱在怀里(执行母亲的eventHandler),同时母亲获得了小孩子的一些参数($event.rating)

1、@input()

父组件 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"
      },
      {
        "id": 3,
        "name": "angular"
      },
      {
        "id": 4,
        "name": "ionic"
      },
      {
        "id": 5,
        "name": "node"
      }
    ]
  }
}

模板文件 father.html

<h1>父组件</h1>
// 包含子组件, 并使用属性传递数据过去
<my-child [info]="data"></my-child>

子组件 child.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>

2、@Output()

子组件three-link.component.ts

1. 引入

import {Component, OnInit, Output, EventEmitter} from "@angular/core";

2. 定义输出变量

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

3. 事件出发,发射变量给父组件

provinceChange() {
  // 选择省份的时候发射省份给父组件
  this.provinceOut.emit(this.province);
}

父组件模板

<!--三级联动组件-->
<three-link (provinceOut)="recPro($event)"></three-link>

父组件

// 函数接受子函数传递过来的变量, 子函数中emit的时候触发这个函数。
recPro(event) {
  this.province = event;
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们