1.1 @Input

一个装饰器,用来把某个类字段标记为输入属性,并提供配置元数据。 该输入属性会绑定到模板中的某个 DOM 属性。当变更检测时,Angular 会自动使用这个 DOM 属性的值来更新此数据属性。

1.2 @Output

一个装饰器,用于把一个类字段标记为输出属性,并提供配置元数据。 凡是绑定到输出属性上的 DOM 属性,Angular 在变更检测期间都会自动进行更新。

1.3 实际代码

1.3.1 SonComponent 与 html

  该模板使用@Input 装饰的 item 接收父模板传过来的数值,使用 @Output 模板装饰 update 向父模弹出事件。

 1 import {Component, EventEmitter, Input, Output} from '@angular/core';
 2 
 3 /**
 4  * @author pancc
 5  * @version 1.0
 6  */
 7 @Component({
 8   selector: 'app-son',
 9   templateUrl: './son.component.html',
10   styleUrls: ['./son.component.css']
11 })
12 export class SonComponent  {
13 
14   @Input()
15   item: string;
16 
17   @Output()
18   update: EventEmitter<string> = new EventEmitter<string>();
19 
20   constructor() {
21   }
22   emitString() {
23      this.update.emit(this.item);
24   }
25 }

  该页面定义了一个方法,当对 p 标签内的 son Works! 点击后发生一个 emitter 冒泡事件(在这里将父模板传进来的 string 值向上弹),该事件由父模板接收。

1 <div id="son" style="  border-radius: 14px ;
2   border: #deff86 2px solid;
3   margin-right: 12px;
4   padding: 1px;">
5   <p (click)="emitString()" style="background-color: #deff86">son works! </p>
6   <p style="text-align: center;background-color: aqua;" class="item">{{item}}</p>
7 </div>

1.3.2 FatherComponent 与 html

  该模板在初始化的时候产生 4 个随机的字母,并且放入 items 中

 1 import {Component, OnInit} from '@angular/core';
 2 import * as Chance from 'chance/chance.js';
 3 
 4 /**
 5  * @author pancc
 6  * @version 1.0
 7  */
 8 @Component({
 9   selector: 'app-father',
10   templateUrl: './father.component.html',
11   styleUrls: ['./father.component.css']
12 })
13 export class FatherComponent implements OnInit {
14   message: string;
15   items: string[] = [];
16 
17   constructor() {
18   }
19 
20   doUpdate(i: string) {
21     this.message = ` father receives ${i}`;
22   }
23 
24   ngOnInit(): void {
25     const size = 4;
26     for (let i = 0; i < size; i++) {
27       this.items.push(Chance().character());
28     }
29 
30     console.log(this.items);
31   }
32 }

  该页面遍历 items ,并将items中的每一个数值传进子模板,并定义了一个方法 doUpdate 接收子模板的 emitter 事件。

1 <div style="float: left" >
2 <p style="text-align: center">{{message?message:'father waits for message!'}}</p>
3 <div *ngFor="let i of items" style="float: left;">
4   <app-son [item]="i" (update)="doUpdate(i)"  ></app-son>
5 </div>
6 </div>

1.4 测试

 当点击第一个 div 内的 son works! 文字时,message 发生改变:

 当点击第二个 div 内的 son works! 文字时,message 同样发生改变:

 

 

 

 

 

 

 

 

 

posted on 2019-11-18 23:09  四维胖次  阅读(281)  评论(0编辑  收藏  举报