typescript 如何以动态角度形式获取更改事件的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49485292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get values on change event in dynamic angular forms?
提问by Talk is Cheap Show me Code
On component.ts file I am fetching the form field values in json array like this and converting it to an FormGroup control like this. This is working perfectly fine.
在 component.ts 文件中,我像这样获取 json 数组中的表单字段值,并将其转换为这样的 FormGroup 控件。这工作得很好。
getJsonForm(){
let base_url = 'example.org'
let getform_query = '/Base/formfieldsgenerator_get';
let getform_endpoint = base_url.concat(getform_query);
this.AllFormData = [];
this.http.get('getform_endpoint'.'?tabpgrpid='+this.tabpgrpid+'&tabgrpname='+this.tabgrpname+'&usertabgrpname='+this.usertabgrpname+'&moduleid='+this.moduleid+'&templateid='+this.templateid+'&all_mod_data='+this.all_mod_data,{headers: this.headers}).subscribe(
res => {
this.AllFormData = res;
// this array is used to iterate in html side
this.newfdata[element] = [];
this.newfdata[element]['properties'] = [];
Object.keys(res['com'][element]['schema']['properties']).forEach(inputKey => {
this.newfdata[element]['properties'].push(res['com'][element]['schema']['properties'][inputKey]);
});
// this is used to create form controls and form groups
this.objectProps = Object.keys(res['com'][element]['schema']['properties']).map(prop => {
return Object.assign({}, { key: prop} , res['com'][element]['schema']['properties'][prop]);
});
for(let prop of Object.keys(res['com'][element]['schema']['properties'])) {
formGroup[prop] = new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));
}
});
this.form = new FormGroup(formGroup);
});
}
Now on components.html side I am using the array like this to generate the dynamic form. This is also working fine.
现在在 components.html 方面,我使用这样的数组来生成动态表单。这也工作正常。
<form (ngSubmit)="custom_submit(form.value)" [formGroup]="form" >
<div *ngFor="let input1 of newfdata[tabname].properties">
<ng-container *ngIf="input1.type=='string'">
<div>
<mat-form-field>
<input matInput [formControlName]="input1.field_name" [id]="input1.field_name" type="text" placeholder="{{input1.title}}">
</mat-form-field>
</div>
</ng-container>
</div>
</form>
Now I want to change the value of one form field based on changes on previous form fields. For that I am not able to subscribe to the valuechanges emitter of the form group variable.
现在我想根据先前表单字段的更改来更改一个表单字段的值。为此,我无法订阅表单组变量的 valuechanges 发射器。
I have tried this on ngOnit but it's not working and not producing any result in console.
我已经在 ngOnit 上尝试过这个,但它不起作用并且在控制台中没有产生任何结果。
ngOnit(){
this.form.valueChanges.subscribe(val => {
this.formattedMessage = 'My changed values for is ${val}.';
console.log(this.formattedMessage);
});
}
Edit 1 :
编辑1:
After suggestion from Manzur Khan, I have passed the valueas true for the success of formcreated event and then in ngOnit used the value like this to get the onchange event :
根据 Manzur Khan 的建议,我已经将 formcreated 事件成功的值传递为 true,然后在 ngOnit 中使用这样的值来获取 onchange 事件:
this.form = new FormGroup(formGroup);
this.dataService.change_current_form_created("true");
and in NgonIt
在 NgonIt 中
this.dataService.last_form_craeted_message.subscribe(data => {
if(data=="true") {
this.form.valueChanges.subscribe(val => {
this.formattedMessage = 'My changed values for is ${val}.';
console.log(this.formattedMessage);
});
}
});
Now I am able to log on change event in console but not able to get the resolution for ${val}.
现在我可以在控制台中登录更改事件,但无法获得 ${val} 的分辨率。
Edit 2 :
编辑2:
Since the val is object, I was not able to resolve ${val} somehow,I Simply did
由于 val 是对象,我无法以某种方式解析 ${val},我只是做了
this.form.valueChanges.subscribe(val => {
console.log('the changed value is',val);
});
It gives me all the values of given formgroups. I still need to optimize this result further so that I just listened to specific form controls. But it has give me a road to go. Thanks all.
它为我提供了给定表单组的所有值。我仍然需要进一步优化这个结果,以便我只听特定的表单控件。但它给了我一条路要走。谢谢大家。
回答by Manzur Khan
It's happening because you are listening to value changes of the form even before the form is present(since it's inside async)
发生这种情况是因为您甚至在表单出现之前就在监听表单的值变化(因为它在异步内部)
You can try something like this
你可以试试这样的
First declare an Observable
首先声明一个 Observable
formCreated: Subject<boolean> = new Subject();
Then in your form code
然后在你的表单代码中
this.form = new FormGroup(formGroup);
this.formCreated.next(true)
and then in your ngOnInit
然后在你的 ngOnInit
this.formCreated.subscribe(data => {
if(data) {
this.form.valueChanges.subscribe(val => {
this.formattedMessage = 'My changed values for is ${val}.';
console.log(this.formattedMessage);
});
}
})
回答by Boanta Ionut
Instead of
代替
formGroup[prop] = new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));
Try to add controls to the form, it worked for me. You can do that by using form.addControl:
尝试向表单添加控件,它对我有用。你可以通过使用 form.addControl 来做到这一点:
formGroup.addControl(prop, new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));
回答by mayur
I still need to optimize this result further so that so that I just listened to specific form controls?? , I have some different solution for you which may work for your requirements.
我仍然需要进一步优化这个结果,以便我只听特定的表单控件??,我为您提供了一些不同的解决方案,它们可能适合您的要求。
template.html
模板.html
<form (ngSubmit)="custom_submit(form.value)" [formGroup]="form" >
<div *ngFor="let input1 of newfdata[tabname].properties">
<ng-container *ngIf="input1.type=='string'">
<div>
<mat-form-field>
<input matInput (ngModelChange)="modelChanged($event,input1.field_name)"[formControlName]="input1.field_name" [id]="input1.field_name" type="text" placeholder="{{input1.title}}">
</mat-form-field>
</div>
</ng-container>
</div>
</form>
component.ts
组件.ts
public modelChanged(ev, formName) {
console.log('Jarvis Event', ev);
console.log('control value', this.form.get(formName).value);
}
回答by Sher Singh
We can use form controlobject to create an event on a particular dynamic form HTML element. e.g.
我们可以使用表单控件对象在特定的动态表单 HTML 元素上创建事件。 例如
this.form.controls["DynamicFormControlId"].valueChanges.subscribe(val => {
});