逐步教会你使用angular组件的输入@input()与输出@Output()

632 阅读2分钟

组件的输入输出通常用来进行父子组件间传值

使用方法:

1.@Input:当子组件的某些属性值需要由调用它的父组件决定时,使用@Input

(1)子组件先从angular/core中引入Input

(2)子组件在class类中声明输入属性的属性名

// child.component.ts
@Input() menus;

(3)父组件调用子组件并绑定输入属性,此时是属性绑定,在angular中,属性绑定用方括号

注:1.方括号中是被绑定的子组件的输入属性,等号后的属性是父组件绑定的属性名,该属性名不必与子组件输入属性名保持一致

2.如果子组件输入属性用了方括号,那么等号后面的双引号内的代码格式就是可执行的js代码,如果不带方括号,那么等号后面的双引号内的代码格式就是字符串,如进行的是颜色的绑定就有两种方法:titleColor = "red"[titleColor]="'red'"

// parent.component.html
<child [menus]="menus"></child>

(4)父组件在自身class类中为子组件输入属性传值

// parent.component.ts
menus="{xxx: yyy}";

2.@Output:当子组件发生某个事件需要向父组件传递信息时,使用@output

(1)子组件先从angular/core中引入Output和EventEmitter

(2)子组件在自身class类中声明输出属性名

// child.component.ts
@Output() tabSelected = new EventEmitter();

(3)在自组件某个事件中使用输出属性,当调用该事件时,会向父组件传递信息

// child.component.ts
handleSelection() {
handleSelection(index: number) {
    this.selectionIndex = index;
    this.tabSelected.emit(this.menus[this.selectionIndex]);
  }
}

(4)父组件在调用子组件时绑定输出属性,此时是事件绑定,在angular中,事件绑定用小括号

// parent.component.html
<child (tabSelected)="handleSelection($event)"></child>

此时,触发子组件的handleSelection方法,就会激活子组件的tabSelected事件,就会激发父组件的handleSelection(不必与子组件方法同名)方法,其中$event就是子组件传递过来的信息

在父组件中声明和子组件输出属性绑定的方法

// parent.component.ts
handleSelection(event) {
    console.log(event);
}

以上,就会在控制台打印出子组件传递过来的this.menus[this.selectionIndex]