从子函数执行父函数;t更新父级'的属性

Executing a parent function from child doesn't update the parent's properties

本文关键字:属性 子函数 执行 函数 更新      更新时间:2024-04-12

在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();
  }
}