[英]How to parse and populate the value from one field into an another in Angular 2
[英]Angular populate components from one place to other
我是 angular 的新手,我正在嘗試實現以下情況:假設我有一個表單控件 A,它具有:
<div class="col-sm-9">
<mat-form-field class="example-full-width" appearance="outline">
<mat-label> Case1 </mat-label>
<textarea spellcheck="true" matInput placeholder="" formControlName="A" cols="100"
</mat-form-field>
</div>
<div class="col-sm-9">
<mat-form-field class="example-full-width" appearance="outline">
<mat-label> Case2 </mat-label>
<textarea spellcheck="true" matInput placeholder="" formControlName="A" cols="100"
</mat-form-field>
</div>
假設我有其他表單控件 B,它具有:
<div class = "col-sm-12">
<mat-form-field class="example-full-width" style = "margin-top:10px;" appearance="outline">
<mat-label>comment #{{i+1}}</mat-label>
<textarea spellcheck="true" matInput placeholder="" formControlName="B" cols="100" rows="10"></textarea>
</mat-form-field>
</div>
現在,如何使用表單 A 的 case1 和 case2 值(如果已輸入)填充“評論”字段?
非常感謝任何幫助/指導,謝謝。
我建議為兩個輸入設置不同的formControlName
,否則,無論您在第一個輸入中使用A
輸入什么值,都將反映在第二個輸入中,因為它們都具有與A
相同的表單控件名稱。
由於您使用的是formControlName
,意味着您使用的是ReactiveForms
方法,這意味着,在組件代碼的某處,您已經通過使用FormBuilder
或FormControl
創建了 javascript object 的表單,例如:
myForm!: FormGroup;
constructor(private fb: FormBuilder) {} // using FormBuilder
ngOnInit(): void {
this.myForm = this.fb.group({
A: ['', Validators.required],
B: [''],
C: ['']
});
}
所以,如果你想用你的輸入控件A
實時填充你的輸入,你可以通過使用返回observable
的valueChanges
來實現。
模板 HTML
<input formControlName="A" type="text"/>
<input formControlName="B" type="text"/>
零件
ngOnInit(): void {
...
this.myForm.get('A').valueChanges.subscribe((value) => {
this.myForm.get('B').patchValue(value);
})
}
不要忘記管理訂閱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.