详解Angular2中Input和Output用法及示例

时间:2019-03-30
本文章向大家介绍详解Angular2中Input和Output用法及示例,主要包括详解Angular2中Input和Output用法及示例使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

对于angular2中的Input和Output可以和AngularJS中指令作类比。

Input相当于指令的值绑定,无论是单向的(@)还是双向的(=)。都是将父作用域的值“输入”到子作用域中,然后子作用域进行相关处理。

Output相当于指令的方法绑定,子作用域触发事件执行响应函数,而响应函数方法体则位于父作用域中,相当于将事件“输出到”父作用域中,在父作用域中处理。

看个angular2示例吧,我们定义一个子组件,获取父作用域的数组值并以列表形式显示,然后当点击子组件的元素时调用父组件的方法将该元素删除。

//app.component.html
<app-child [values]="data" (childEvent) = "getChildEvent($event)">
</app-child>

//app.component.ts
@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 data = [1,2,3];

 getChildEvent(index){
  console.log(index);
  this.data.splice(index,1);
 }
}

以上是跟组件app-root的组件类及模板,可以我们把data输入到子组件app-child中,然后接收childEvent事件并对其进行响应。

//app-child.component.html
<p *ngFor="let item of values; let i = index" (click)="fireChildEvent(i)">
 {{item}}
</p>


//app-child.component.ts
@Component({
 selector: 'app-child',
 templateUrl: './child.component.html',
 styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
 @Input() values;
 @Output() childEvent = new EventEmitter<any>();
 constructor() { }

 ngOnInit() {

 }
 fireChildEvent(index){
  this.childEvent.emit(index);
 }
}

子组件定义了values接收了父组件的输入,这里就是data值,然后使用ngFor指令显示。

当点击每个元素的时候触发了click事件,执行fireChildEvent函数,该函数要将元素的index值“输出”到父组件中进行处理。

Output一般都是一个EventEmitter的实例,使用实例的emit方法将参数emit到父组件中,触发父组件的childEvent事件。

然后父组件监听到该事件的发生,执行对应的处理函数getChildEvent,删除传递的元素索引指向的数据,同时,视图更新。

实际效果:

源码地址:https://github.com/justforuse/angular2-demo/tree/master/angular-input-output

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。