angularjs – Angular2:子组件访问父类变量/函数
发布时间:2020-12-17 08:31:02 所属栏目:安全 来源:网络整理
导读:我在父组件中有一个可能被child改变的变量,parent将在视图中使用这个变量,因此必须传播更改。 import {Component,View} from 'angular2/core';@Component({selector: 'parent'})@View({ directives: [Child],template: `childcomp/childcomp`})class Paren
我在父组件中有一个可能被child改变的变量,parent将在视图中使用这个变量,因此必须传播更改。
import {Component,View} from 'angular2/core'; @Component({selector: 'parent'}) @View({ directives: [Child],template: `<childcomp></childcomp>` }) class Parent { public sharedList = new Array(); constructor() { } } @Component({selector: 'child'}) @View({template: `...`}) class Child { constructor() { //access 'sharedList' from parent and set values sharedList.push("1"); sharedList.push("2"); sharedList.push("3"); sharedList.push("4"); } }
如果使用带有JavaScript引用类型(例如,Object,Array,Date等)的input属性数据绑定,则父和子都将引用同一/一个对象。对共享对象所做的任何更改都将对父和子都可见。
在父级模板中: <child [aList]="sharedList"></child> 在孩子: @Input() aList; ... updateList() { this.aList.push('child'); } 如果要在构建子项时向列表中添加项目,请使用 ngOnInit() { this.aList.push('child1') } 这个Plunker shows a working example,在父组件和子组件中的按钮,都修改共享列表。 注意,在孩子中你不能重新分配引用。例如,不要在孩子中这样做:this.aList = someNewArray;如果这样做,那么父组件和子组件将分别引用两个不同的数组。 如果你想共享一个原始类型(即,字符串,数字,布尔),你可以把它放入一个数组或一个对象(即,把它放在一个引用类型),或者你可以emit每当原始值改变(即,让父监听自定义事件,并且孩子将有一个EventEmitter输出属性。更多信息参见@ kit的答案。) 更新2015/12/22:Structural Directives指南中的重装载器示例使用上面介绍的技术。主/父组件具有绑定到子组件的logs数组属性。子组件push()到数组,父组件显示数组。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |