Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 是否可以根据其所在的父组件在可重用子组件中执行函数?_Angular - Fatal编程技术网

Angular 是否可以根据其所在的父组件在可重用子组件中执行函数?

Angular 是否可以根据其所在的父组件在可重用子组件中执行函数?,angular,Angular,我有一个可重用的ChildComponent,它包含一个带有选项的select。我在多个父组件中使用此组件。我想在子组件中执行不同的函数,具体取决于发生(更改)的父组件。因此,如果在例如ParentComponent1中发生更改,我希望执行parent1\u函数()。如果更改发生在ParentComponent2中,我想执行parent2\u函数()。使用angular和(如果不是的话)什么是干净的解决方案,而不必重写每个父组件中的select,这是否可行?您可以将父组件名称作为@Input 父

我有一个可重用的
ChildComponent
,它包含一个带有选项的select。我在多个父组件中使用此组件。我想在子组件中执行不同的函数,具体取决于发生
(更改)
的父组件。因此,如果在例如
ParentComponent1
中发生更改,我希望执行
parent1\u函数()。如果更改发生在
ParentComponent2
中,我想执行
parent2\u函数()。使用angular和(如果不是的话)什么是干净的解决方案,而不必重写每个父组件中的select,这是否可行?您可以将父组件名称作为
@Input

父HTML:

<app-child [parent]="'parent1'"></app-child>

儿童TS:

@Input()父项:字符串

子HTML:


(更改)=“parent=='parent1'?parent1_function():parent2_function()”

带有Maryannah注释

在父组件中

在child.component.ts中

@Input() public parentFunction1: Function;

ngOnInit(){
     this.parentFunction1(this.getItems());
}
@Output()value_change=neweventemitter();
..
//其他逻辑
..
onValueChange(){
值\u更改。发射(选定值)

}

如果您使用特殊的父组件,您希望在您的子组件中执行特殊的函数吗

像parent1一样,在childComponent中使用function1。parent2在childComponent中使用function2

函数1和函数2正在子组件中使用函数3。像这样的

然后我会使用回调函数

parent1.component.ts:

  function1(items: any) {
    // do something
  }
parent1.component.html

<app-child [parentFunction1]="function1"></app-child>

这是一种可怕的做法,因为它将父母和孩子紧密地结合在一起。这意味着子级必须具有指定的父级,并且无法正确重用。是。。我明白,但这是要求。除非绝对必要,否则不应使用此选项。这不是要求,对于一个笨拙的问题,这是一个糟糕的实现。如果您可以实现这一点,那么您可以在子对象中实现一个
@Output
,以实现与您在这里描述的完全相同的过程。如果子对象必须对父对象的事件做出反应,然后发出一个事件来触发父对象函数,那么通过传递性,您只需要父对象,因为子对象已变得无用。请仔细解释你的问题!