从子函数执行父函数;t更新父级'的属性
Executing a parent function from child doesn't update the parent's properties
在Angular 2中,您经常使用this
,这很好,但我发现,当您想将函数向下传递到组件层次结构时,它也会产生问题。
举个例子:
export class ParentComponent {
myFunctionFromParent() {
this.isActive = true;
}
}
然后我们把这个函数传给一个子函数:
<parent>
<child [onClick]="myFunctionFromParent"></child>
</parent>
假设child
是一个简单的按钮:
<button (click)="onClick()"></button>
现在,当myFunctionFromParent
运行时,this
应该是ParentComponent
,但它不是。
相反,ChildComponent
将更改其this.isActive
属性。
这会产生很多问题,因为您无法从子组件执行父函数,并且期望父属性发生更改。
传递函数的工作方式正如您在Angular 1中所期望的那样,但现在它似乎已经崩溃了。
这不再是做这种事情的方式了吗?在Angular 2中,正确的方法是什么?
不用传递函数,而是使用带有输入和输出的默认角度数据绑定:
class ParentComponent {
myFunctionFromParent() {
this.isActive = true;
}
}
class ChildComponent {
@Output() onClick = new EventEmitter();
}
<parent>
<child (onClick)="myFunctionFromParent()"></child>
</parent>
<button (click)="onClick.emit()"></button>
我会用这个来代替:
<parent>
<child (onClick)="myFunctionFromParent()"></child>
</parent>
并在子组件中定义CCD_ 8
@Component({
selector: 'child',
template: `
<button (click)="onClick()"></button>
`
})
export class ChildComponent {
@Output('onClick')
eventHandler:EventEmitter<any> = new EventEmitter();
onClick() {
this.eventHandler.emit();
}
}
相关文章:
- 如何在JavaScript中实现子函数
- 单击从子函数返回父函数
- 将子函数的JavaScript字符串转换为实际函数
- 作为原型的函数的子函数
- 覆盖上下文.属性和函数
- 主干 where 对作为对象的属性的函数
- 不引人注目地设置属性后函数失败
- 使用onclick调用属性对象函数
- 如何在父动画开始时激发jquery子函数
- 从子函数执行父函数;t更新父级'的属性
- 用于更改object.object属性的函数
- 如何在子函数中返回值
- Javascript对象属性和函数
- 如何运行由jquery attr添加到onsubmit属性的函数
- 调用子函数时阻止父jquery函数
- 如何在我的setAttribute函数中构建数组中的子函数
- 复制不带属性的函数引用
- 将变量传递给子函数 javascript
- JavaScript:基于数组中包含的对象属性生成函数
- 在Ember.js中访问包含有序内容的子函数/属性