Angular2 - call a function from another standalone component. Basically, call function from outside component

261 views Asked by At

I'm loading in a component (Component1) another standalone component(Component2) that contains a form.

Imagine you have made a form component and I want to integrate it in my component and trigger the submit function you have written, without clicking on your submit Button.

The submit button on this form triggers a function to save data:

submitData(newUserForm: NgForm)

The main component (Component1) also has a submit button. What I want is to remove the submit button from Component2 and trigger the submit function when I click on submit from Component1.

Something like:

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

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

ViewChild won't work since the 2 components are not part of the same component. Also, output won't work.

What options do I have to call the function from outside Component2?

I hope you can help.

Thank you.

Regards, AG

3

There are 3 answers

0
Manuel Fabri On

Without much context, I think you need a service to do this. If there's no relation between those 2 components, why would you call a function from component 2? Put save logic into a service and inject it on whatever component you need it.

0
AudioBubble On

Use a service here

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

Component 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);
        }
    });
}

Component 1 TS

constructor(private someService: SomeService){
}

saveData(): void {
    this.someService.theValue = 'Saved';
}
0
Liu Zhang On

This is about the component interaction, you need to use service for communicating between two different components. Main thing is the dependency injection of Angular.

Simply you can use Subject.