猿问

Angular:在FormGroup中定义默认值输入FormField

从下面的代码中可以看出,我将默认值设置为文本区域:


<form [formGroup]="entryForm" (ngSubmit)="onSubmit()">

     <div class="view">

            <div class="col">

                        <mat-form-field>

                            <textarea matInput value="Test..." formControlName="firstValue"></textarea>

                        </mat-form-field>

            </div>

            <button type="submit">Submit</button>

      </div>

</form>

我正在初始化我的 FormGroup 和 FormFields,如下所示:


ngOnInit() {

 this.entryForm = new FormGroup({

   firstValue: new FormControl('')

 });

}


public onSubmit() {

  console.log(this.entryForm.value);

}

但是当我点击提交时,值firstValue似乎是空的,而不是“测试...”值,就像在 dom 元素中定义的一样。


潇湘沐
浏览 514回答 3
3回答

繁花不似锦

改变这个:firstValue:&nbsp;new&nbsp;FormControl('')对此:firstValue:&nbsp;new&nbsp;FormControl('Test...')并从文本区域中删除属性值:<textarea&nbsp;formControlName="firstValue"></textarea>在这里,您可以找到一个完整的工作示例(基于此答案)笔记:这种方法的问题是初始 Textarea 值将是“Test...”,这意味着用户将看到这样的文本。

慕尼黑5688855

模板文件:您formNameControl的不正确:你可以看看这个演示可能对你有帮助!&nbsp; <form [formGroup]="entryForm" (ngSubmit)="onSubmit()">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<div class="lang">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="lang-col">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <textarea&nbsp; formControlName="firstValue">&nbsp; &nbsp;</textarea>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="submit">Submit</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </form>类文件entryForm: FormGroup;&nbsp; ngOnInit() {&nbsp; &nbsp; this.entryForm = new FormGroup({&nbsp; &nbsp; &nbsp; firstValue: new FormControl('Test...')&nbsp; &nbsp; });&nbsp; }&nbsp; onSubmit() {&nbsp; &nbsp; console.log(this.entryForm.value);&nbsp; }或者您可以检查是否formControlName为空然后设置默认值&nbsp; onSubmit() {&nbsp; &nbsp; if(this.entryForm.get('firstValue').value == "") {&nbsp; &nbsp; &nbsp; this.entryForm.patchValue({&nbsp; &nbsp; &nbsp; &nbsp; firstValue: 'Your defualt value goes here'&nbsp; &nbsp; &nbsp; });&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; console.log(this.entryForm.value);&nbsp; }

蝴蝶刀刀

作业中的问题。你必须在类定义之后分配你的输入表单的值,像这样export class MyComponent implements OnInit{&nbsp; &nbsp; public entryForm: FormGroup = new FormGroup({&nbsp; &nbsp; &nbsp; &nbsp; firsValue: new formControl('')&nbsp; &nbsp; });&nbsp; &nbsp; constructor()&nbsp; &nbsp; ngOnInit()}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答