【问题标题】:Angular2 - call a function from another standalone component. Basically, call function from outside componentAngular2 - 从另一个独立组件调用函数。基本上,从外部组件调用函数
【发布时间】:2021-07-25 21:05:14
【问题描述】:

我正在一个组件(Component1)中加载另一个包含表单的独立组件(Component2)。

假设你做了一个表单组件,我想将它集成到我的组件中,并触发你编写的提交功能,而不需要点击你的提交按钮。

此表单上的提交按钮触发保存数据的功能:

submitData(newUserForm: NgForm)

主组件(Component1)也有一个提交按钮。我想要的是从 Component2 中删除提交按钮,并在我单击 Component1 中的提交时触发提交功能。

类似:

<button type="button" class="submit" (click)="saveData()">{{ Save }}</button>

saveData() {
     Component2.submitData(data);
}

ViewChild 不起作用,因为这 2 个组件不是同一个组件的一部分。此外,输出将不起作用。

我必须从 Component2 外部调用该函数的哪些选项?

希望你能帮忙。

谢谢。

问候, AG

【问题讨论】:

  • 您可以使用可以在两个组件中注入的服务或 redux -> ngrx 来实现此目的

标签: javascript angular angular2-forms


【解决方案1】:

没有太多上下文,我认为您需要一项服务来执行此操作。如果这两个组件之间没有关系,为什么要从组件 2 调用函数? 将保存逻辑放入服务中,并将其注入到您需要的任何组件中。

【讨论】:

    【解决方案2】:

    在此处使用服务

    SomeService

    private value: Subject<string> = new Subject<string>();
    
    // return the Subject as an Observable in order to be able to subscribe to it
    public get theValue(): Observable<string> {
        return this.value.asObservable();
    }
    
    // set the current value
    public set theValue(value: string) {
        this.value.next(value);
    }
    

    组件 2 TS

    constructor(private someService: SomeService){
    
    }
    
    ngOnInit(): void {
        // subscribe to the value and refresh the local variable whenever it changes
        this.someService.theValue.subscribe( value => {
            console.log('Info from Component 1: ' + value;
    
            if (value === 'Saved') {
                Component2.submitData(data);
            }
        });
    }
    

    组件 1 TS

    constructor(private someService: SomeService){
    }
    
    saveData(): void {
        this.someService.theValue = 'Saved';
    }
    

    【讨论】:

      【解决方案3】:

      这是关于组件交互的,你需要使用服务来在两个不同的组件之间进行通信。主要是Angular的依赖注入。

      只需使用主题即可。

      【讨论】:

        猜你喜欢
        • 2017-01-09
        • 1970-01-01
        • 1970-01-01
        • 2017-05-02
        • 1970-01-01
        • 2017-07-13
        • 2017-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多