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!'; } }
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!';
}
}