SNnaKR
SNnaKR

Reputation: 17

How to reset forms from another unrelated component in angular

I got several (template-driven-forms) in my application and want to reset them all when one central button is beeing pressed. My idea was to call all those reset() functions in a function that is located in a service. The problem with that approach is that I don't know how I can call this reset functions. All the examples I found have been with data but in my case I just want to call the components functions without sending data. Other approaches how to handel a central reset are also welcome schematic idea

Here is a minimal code example. It does not work properly because of some import problems but at least you can see the code. Hope it is okay anyways https://stackblitz.com/edit/angular-ivy-vp2cjo?file=src%2Fapp%2Fname%2Fname.component.ts

Upvotes: 0

Views: 1069

Answers (2)

lovis91
lovis91

Reputation: 2171

Your schematic idea is fine, you need to create a service like :

export class myService {
  reset: boolean = false;

  private emitChangeSource = new BehaviorSubject<boolean>(this.reset);
  changeEmitted$ = this.emitChangeSource.asObservable();

  emitChange(change: any) {
    this.emitChangeSource.next(change);
  }

  constructor() { }
}

And then, you subscribe in your components like :

this.myService.changeEmitted$.subscribe(data => {
    if (data) {
        this.form.reset();
    }
 });

To fire the change you use:

this.myService.emitChange(true);

Upvotes: 2

Blackturtok
Blackturtok

Reputation: 16

I am not 100 % sure if this helps you, but I know a way to call a function from another component. With Viewchild you can't access function directly, but you can access variables, so my solution would be to set a lampda function into a variable that calls your reset function. example displaying component

public resetCommand = () => {this.reset()}

example controling compontent

Viewchild ... myDisplay
callingReset()
{
    this.myDisplay['resetCommand']();
}

Upvotes: 0

Related Questions