简体   繁体   English

Angular 表单中的明文区域值,但应存在表单值

[英]Angular clear textarea value in form, but form value should be present

I'm using Reactive forms in angular I have an textarea and an add button, when I enter some value in textarea and click on add button an link will be generated above the text area, after each value is added i want to clear the textarea,but the value should be present in the form.我在 angular 中使用 Reactive forms 我有一个 textarea 和一个添加按钮,当我在 textarea 中输入一些值并单击添加按钮时,将在文本区域上方生成一个链接,添加每个值后我想清除 textarea ,但该值应存在于表单中。

<form [formGroup]="myForm">
<div *ngFor="let item of links">
<a href="{{ item.link }}" target="blank">{{ item.link }}</a>
</div>
<div>
<textarea formControlName="documentLink"></textarea>
<button type="submit" (click)="addlink(myForm)">Add</button>
</div>
</form>

export class AppComponent {
public documentLink: string[] ;
public links = Array<{ link: string }>();
public myForm: FormGroup = new FormGroup({
documentLink: new FormControl()});
public linkdata=[]
addlink(data: any) {
if(data.value.documentLink==''){
alert("Please enter valid link");
return;
}
else
{
this.links.push({ link: data.value.documentLink });
for(let i=0;i<this.links.length;i++){
this.linkdata.push(this.links[i].link)
}
this.myForm.setValue({documentLink: this.linkdata})
console.log(this.myForm.value)
} 
}

There is no built-in solution with Reactive Forms to suit your use case.反应式 Forms 没有适合您的用例的内置解决方案。 Except if you have another for this.links and this.linkdata they sounds like duplicates.除非你有另一个this.linksthis.linkdata他们听起来像重复。

Here is a solution storing each link inside an array and resetting the form value each time:这是一个将每个链接存储在数组中并每次重置表单值的解决方案:

links: string[] = []
addLink() {
 if (this.myForm.value.documentLink === '') {
  return;
 }
 this.links = [...this.links, this.form.value.documentLink];
 this.myForm.get('documentLink').reset();

}

I would like to understand... Why do you need to keep the value in the form?我想了解...为什么需要保留表单中的值? However, I think You can't, the reactive forms use two-way data binding.但是,我认为您不能,反应式 forms 使用双向数据绑定。 So if you change any of those, it will replace the other.因此,如果您更改其中任何一个,它将替换另一个。

One idea would be using an onChange() event and create a variable with the latest value, so when it changes you will update that variable with the latest value of the form.一个想法是使用 onChange() 事件并使用最新值创建一个变量,因此当它更改时,您将使用表单的最新值更新该变量。 So you can access to that value when you need it.因此,您可以在需要时访问该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM