I am learning Angular and I am trying to do the following:
I want there to be an input of text and a button followed by a paragraph tag. I would like the text from the input to be displayed in the paragraph only when the button is pressed. I have done this so far:
<input type="text" />
<button (click)="saveText($event)">Save</button>
<p>{{ paragraphText }}</p>
export class ServersComponent implements OnInit {
paragraphText = '';
constructor() { }
saveText(event: any) {
this.paragraphText = (<HTMLInputElement>event.target).value;
}
If I use ngModel
that is a two-way data binding and that constantly updates the text in paragraph. However, I want it to be done only when the button Save
is pressed.
I'll really appreciate the help.
CodePudding user response:
Without ngModel it can be achieved with template reference for input and value of that input when you click button.
component.html
<input type="text" #f [value]="text" />
<button (click)="onUpdateText(f.value)">Save</button>
<p>{{ text }}</p>
component.ts
export class AppComponent {
text = '';
onUpdateText(value: string): void {
this.text = value;
}
}
CodePudding user response:
You could use 2 properties, one for the model and one for the pharagraph. Like this:
<input type="text" [(ngModel)]="textValue" />
<button (click)="saveText()">Save</button>
<p>{{ paragraphText }}</p>
export class ServersComponent {
textValue = '';
paragraphText = '';
saveText() {
this.paragraphText = this.textValue;
}
}
You can omit the saveText
method too and write this short logic in the (click)
event biding.
<input type="text" [(ngModel)]="textValue" />
<button (click)="paragraphText = textValue">Save</button>
<p>{{ paragraphText }}</p>
If you decide to use a form
, you can change the ngModelOptions to update the property only on submit:
<form>
<!-- name attribute is needed -->
<input
type="text"
name="textValue"
[(ngModel)]="textValue"
[ngModelOptions]="{ updateOn: 'submit' }"
/>
<button>Save</button>
<p>{{ textValue }}</p>
</form>
With this logic you can have only one property.