0

It's possible to reset form inputs value and subsequently set another value from a service? I want to save old value in saveService, reset service and set name attribute of service to Hello World!

So in my saveService i correctly have the old value, but the input in my form remains empty. I've tried also without form reset but nothing.

This is my code:

.html

<form id="formExample">
    <input type="text" id="name" [(ngModel)]="service.name" #name>
</form> 
<button (click)="save()">save</button> 
<button (click)="reset()">reset</button>

.ts

export class Hero {
    constructor(public service: Service, public saveService: SaveService){}
    save(){
        this.saveService.name = this.service.name
    }
    reset(){
        this.service = new Service();
        let form = document.getElementsById('formExample');

        form.reset();

        this.service.name = 'Hello World!';
    }
}
1
  • please post a minimal reproduction on stackblitz so that we can help you out Commented Jan 28, 2020 at 11:25

1 Answer 1

1

If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

<form id="formExample" #myForm>
    <input [ngModelOptions]="{standalone: true}" type="text" id="name" [(ngModel)]="service.name" #name>
</form> 
<button (click)="save()">save</button> 
<button (click)="reset(myForm)">reset</button>

export class Hero {
    constructor(public service: Service, public saveService: SaveService){}
    save(){
        this.saveService.name = this.service.name
    }
    reset(form){
        this.service = new Service();

        form.reset();

        this.service.name = 'Hello World!';
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

OMG Thanks! I didn't even noticed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.