Angular入门之输入输出绑定

入门小白一只,可能部分理解不到位,如有错误望请指正,谢谢~

输入

数据通过输入绑定流入组件,事件通过输出绑定流出你的组件。
[]用来由父组件向子组件传递输入。


父组件:

@component({
  selector:'par-component-name',
  template:`
  '1']="2">
  child-component-name>
  `
})
class par-class-name{
  2;
}

子组件:(两种方法)

方法一:

@component({
  selector:'child-component-name';
  inputs:['3:1']   //inputs:[键值对数组]
})
class kid-class-name{
  3;
}

若3,1同名,即该输入属性的内外名字相同,则可简化为如下,这也是常见情况:

@component({
  selector:'child-component-name';
  inputs:['1']   //inputs:[键值对数组]
})
class kid-class-name{
  1;
}

键值对数组中:
键:3,本组件控制器内的属性名
值:1,出现在HTML标签中,显示外观时的名字


方法二:

@component({
  selector:'child-component-name';
})
class kid-class-name{
  @Input('1') 3;
}

若3,1同名,即该输入属性的内外名字相同,则可简化为如下,这也是Angular风格指南建议的:

@component({
  selector:'child-component-name';
})
class kid-class-name{
  @Input() 3;
}

一个实例:

/**
*@InventoryApp 父组件
*/
@Component({
 selector:'inventory-app',
 template:`
  
"products"> //关键语句
` }) class InventoryApp{ products:Product[]; //父组件声明的属性 constructor(){ this.products=[] } } /** *@ProductList 子组件 */ @Component({ selector:'products-list', inputs:['productList'], //第一种方法 outputs:['onProductSelected'], //输出,下一部分有讲解 template:`` }) class ProductList{ productList: Product[]; //子组件声明的属性 }

输出

()用来由子组件向父组件传递输出。再来重复一遍,数据通过输入绑定流入组件,事件通过输出绑定流出你的组件!!


情况一:输出的事件为组件内置事件
核心语句:(output)=”action”

@component({
  selector:'child-component-name',
  template:`
    
    //即(output)="action",此处只是举例output为点击按钮,可以是任何内置事件的,比如表单里许多控件都可以click,dbl-click,keydown,mousedown,mousemove等;action是本控件控制器内要实现的一个函数
  `

})
class kid-class-name{
  1(){
    //点击按钮后要求执行的动作
  }
}

情况二:输出的事件为自定义事件,来和组件外部通信
其实就是使用了触发事件的情况一,核心语句还是:(output)=”action”,不过这里的output一般是子组件内声明的一个EventEmitter对象,当它通过emit()方法发布事件时,父组件内实现的action函数,用$event参数接收这个事件发出的内容,来执行action函数

如果之前没有接触过观察者模式,可能有点难理解,可以去大概了解下概念就好了

父组件:

@component({
  selector:'par-component-name',
  template:`
  1)="2($event)">   //没错,还是(output)="action"
  
  `
})
class par-class-name{
  2():{}    //一个函数,通常有一个参数,来接收EventEmitter发出的数据
}

子组件:

@component({
  selector:'child-component-name',
  outputs:['1'] ,            //数组,可有多个输出事件属性
  template:`
    
  `
})
class kid-class-name{
  1: EventEmitter<>;

  constructor(){
    this.1=new EventEmitter();
    //当把一个EventEmitter对象赋值给一个输出时,Angular会自动帮我们订阅事件
  }

  3(){                          //这里就是情况一啦
  1.emit("要发送的数据");      //相当于是父组件的函数2订阅了1这个EventEmitter对象,所以1发射的数据会被函数2的$event参数接收到
  }
}

来看一个情况二实际的小例子:

//父组件
@Component({
  selector:'club',
  template:`
    
<single-component (putRingOnIt)="ringWasPlaced($event)",> single-component> ` }) class ClubComponent{ ringWasPlaced(message:string){ console.log(`Put your hands up: ${message}`); //`${message}` 叫做 字符串插值,即显示message的文本内容 } } //子组件 @Compnent({ selector:'single-component'; outputs:[putRingOnIt]; template:`

你可能感兴趣的:(Angular2.0+)