[BUG] Angular 12 form-builder template error
Environment
Please provide as many details as you can:
- Hosting type
- [x] Local deployment
- Version: 5.2.0-rc.1
- [x] Local deployment
Steps to Reproduce
- Create an angular 12 based project
- Add formio as a dependency
- Create a component with form-builder inside it and try to handle the change event
- Project will not build
Expected behavior
Successful build, nothing is done only declaring the components
Observed behavior
Template error
Object is possibly 'undefined'.
Example
The component below will fail to compile
<form-builder [form]="{components: _components}" (change)="onChange($event)"></form-builder>
While the one below will compile successfully when I add optional chain to the change to be change? event
inside the template , which is weird and the editor goes crazy about this marking it as an error , but it passes the angular build
<form-builder [form]="{components: _components}" (change?)="onChange($event)"></form-builder>
How to solve this issue
As a solution, you can pass a bindign property name to the output decorator
export class FormBuilderComponent implements OnInit, OnChanges, OnDestroy {
...
@Output('change') change?: EventEmitter<object>;
...
Shall I raise a pull request for that ?
Note
The linter is complaining that we're using a preserved output name
...the output property "change" should not be named or renamed as a native event.
When I add (change?) instead of only (change) the build is possible, but this does not emit the function onChange($event). So this does not fix the problem with correctly handling the changes made from FormBuilder.
So how to make this think to work with Angular 12 and to handle changes?
try alter the 'change?' for 'change!'
Any news on this topic? I got the same issue.
any workarounds?
Yes, I came across a workaround for this.
Could you share it here @enumahin ?
Component
@ViewChild('json') jsonElement?: ElementRef | any; @ViewChild('formio') formio:any; public form: any = { components: [
]
};
constructor() { }
ngOnInit(): void {
}
saveForm(){ this.jsonElement.nativeElement.innerHTML = ''; this.jsonElement.nativeElement.appendChild(document.createTextNode(JSON.stringify(this.formio.form, null, 4)));
const json = document.createTextNode(JSON.stringify(this.formio.form, null, 4));
console.log(json)
}
HTML
<form-builder [form]="form" #formio> <button (click)="saveForm()" class="btn btn-primary">Save Form
The issue has been fixed
we were using Angular 14 here.. Looks like at some point in time angular introduced strictTemplate option in the tsconfig.json
I had to set tsconfig.json -> angularCompilerOptions -> strictTemplates: false: as a workaround. Hope this helps if anyone else had the same issue.
tsconfig.json:
. . .
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": false // <-------<<< change true to false
}
. . .
}