angularjs2中父子组件的数据传递的实例代码
父到子组件之间的数据传递
父组件模板中引用子组件
// father template: ... <child-item [name] = "fatherItemName" > </child-item> //...`
其中”fatherItemName” 为父组件中的属性,[name] 为子组件的输入
在子组件中使用 @Input() name 来接受父组件传递的值
如果在接收值前需要进行一些处理,可以使用setter 拦截输入属性
_name: string = '';
@Input()
set nameStr(name: string){
_name = "father name:" + name;
}
这时的 _name 作为临时变量,作为set 和get的中转。
父组件中:
< child-item [namestr] = “fatherItemName” >
name -> namestr
使用getter 输出
get nameStr(){ return _name; }
插值时 {{ nameStr }}
子到父组件之间的数据传递
1. 事件传值
// father template: ...
<child-item (childEvent) = "fatherFunction($event)"> </child-item>
//...
export class FatherComponent{
fatherFunction(){
alert('hello!');
}
}
子组件
//...
< p (click) = "clickThis"> click </ p>
//...
@Output() childEvent = new EventEmitter<boolean>();
clickThis(){
this.childEvent.emit();
}
2.父组件通过局部变量获取子组件的引用
<child-item [name] = "fatherItemName" #name > </child-item>
子组件通过#绑定一个name的局部变量来访问子组件的属性
3.使用@ViewChild 获取子组件的引用
@ViewChild(ChildComponent) child: ChildComponent;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Angular 4依赖注入学习教程之Injectable装饰器(六)
这篇文章主要给大家介绍了关于Angular 4依赖注入之Injectable装饰器的相关资料,文中介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来跟着小编一起学习学习吧。2017-06-06
AngularJS 使用ng-repeat报错 [ngRepeat:dupes]
这篇文章主要介绍了AngularJS 使用ng-repeat报错 [ngRepeat:dupes] 的相关资料,需要的朋友可以参考下2017-01-01
Angular.js组件之input mask对input输入进行格式化详解
这篇文章主要给大家介绍了关于Angular.js组件之input mask对input输入进行格式化的相关内容,文中通过示例代码详细介绍了将银行卡号和日期的方法,需要的朋友们可以参考借鉴,下面来一起看看吧。2017-07-07


最新评论