angularjs2中父子组件的数据传递的实例代码
时间:2021-02-19 15:16:59|栏目:AngularJS|点击: 次
父到子组件之间的数据传递
父组件模板中引用子组件
// 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-cli修改端口号【angular2】
栏 目:AngularJS
下一篇:Angularjs Ng_repeat中实现复选框选中并显示不同的样式方法
本文标题:angularjs2中父子组件的数据传递的实例代码
本文地址:http://www.codeinn.net/misctech/65622.html






