【问题标题】:Angular trigger function from outside component来自外部组件的角度触发功能
【发布时间】:2021-07-25 23:18:30
【问题描述】:

我有一个组件,它只包含一个表单和一个提交表单的函数。

submitData(newUserForm: NgForm)

当我点击一个按钮时,如何从另一个组件触发这个功能?

我像这样嵌入表单组件:

<app-form></app-form>

但它不是在主组件中创建的,我无法像子组件一样导入它。

我在主组件中有一个服务,但表单组件无权访问它。

我找到了这个,但似乎没有什么对我有用。

How to call another components function in angular2

在主组件中,我需要一个应该从表单调用提交函数的函数:

类似:

save() {
   submitData();
}

它是否适用于 Hostlistener、dispatchEvent 或 runOutsideAngular 之类的东西?

我找到了一些示例,但似乎没有任何效果。

【问题讨论】:

标签: angular angular2-forms


【解决方案1】:

这是关于组件交互的。只需尝试使用 @ViewChild 装饰器,或者您可以使用服务进行交互。

【讨论】:

  • @ViewChild 不适用于多个组件,而且它必须遵循父子关系。
  • 如果是多个情况,则需要使用@ViewChildren装饰器,并且只要没有父子关系,则需要使用服务。
【解决方案2】:

阅读问题后,我认为您想在父组件上调用“save”方法时调用“form”组件的“submitData”方法。 为此,您可以使用“@Input()”方法。它通常用于将数据从父组件传递到子组件。

所以解决方案如下所示。

在父组件上声明属性

isSubmitted: boolean = false;

然后在父级调用方法“save()”时将此变量设置为true。

save() {
    this.isSubmitted = true;
}

现在将此变量传递给子组件。为此,您需要从父模板文件中传递如下所示的变量。

<app-form [isSubmitted]="isSubmitted"></app-form>

现在我们正在从父组件传递数据,我们需要监听子组件的变化。在子组件中,我们需要声明一个“@Input()”指令,如下所示。

export class Form {

@Input() isSubmitted: boolean;
 ...
}

声明此属性后,我们现在可以在父组件中的变量发生更改时监听更改。

export class Form implements OnChanges {
     @Input() isSubmitted: boolean;
     ...

     // this is the angular life cycle hook which detects changes in input bound properties ( in our case "isSubmitted")
     ngOnChanges(changes: SimpleChanges) {
          if(changes && changes['isSubmitted'].currentValue){
               // calling the submit data method if the "isSubmitted" value changes to "true" from parent component.
               this.submitData(newUserForm: NgForm);
          }
     }
}

这就是父 => 子通信以角度完成的方式。 如有任何疑问,请随时提出。 有关更多信息,您可以查看此链接: parent-child-communication

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 2020-03-08
    • 2020-07-25
    • 2021-01-14
    • 2022-01-15
    • 1970-01-01
    • 2018-01-12
    • 2021-05-16
    • 2018-09-30
    相关资源
    最近更新 更多