@Input

在子组件中

子组件类

  1. import { Component, Input } from '@angular/core';
  2. @Input() item: string; // 使用@Input装饰item属性,用来从父组件中接收数据到item中

子组件模板

  1. // 在子组件模板中显示从父组件获取的数据
  2. {{item}}

在父组件中

父组件模板

  1. <app-child [item]="currentItem"></app-child>

父组件类

  1. export class AppComponent {
  2. // 设置向子组件传输的数据
  3. currentItem = 'Television';
  4. }

@Output

在子组件中

子组件模板

  1. <input type="text" #newItem/>
  2. // 将输入栏的值作为参数,绑定到button的click事件
  3. <button (click)="setItem(newItem.value)">确定</button>

子组件类

  1. import { Output, EventEmitter } from '@angular/core';
  2. // 使用@Output装饰器将newItemEvent暴露到父组件中
  3. @Output() newItemEvent = new EventEmitter<string>();
  4. setItem(value: string): void{
  5. this.newItemEvent.emit(value);
  6. }

在父组件中

父组件模板

  1. {{value}}
  2. <app-child1 (newItemEvent)="changeValue($event)"></app-child1>

父组件类

  1. value: string;
  2. changeValue(value: string): void{
  3. this.value = value;
  4. console.log(value);
  5. }