Reputation: 6735
I am using ngx-formly
, and try to introduce a custom template, which is for view only. When the template is static, it is ok, but if I try to introduce some angular operation, it doesn't work. See this demo. Any suggestions?
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form" (ngSubmit)="submit(model)">
<formly-form [model]="model" [fields]="fields">
<button type="submit">Submit</button>
</formly-form>
</form>
{{ model|json }}
`,
})
export class AppComponent {
form = new FormGroup({});
model = {};
name = "John";
fields: FormlyFieldConfig[] = [
{template: `<div>{{name}}</div>`}, // <-- I expected to see John, but I saw {{name}}
{
key: 'name',
type: 'input',
templateOptions: {
label: 'Field 1',
placeholder: 'Formly is terrific!',
},
},
];
submit(model) {
console.log(model);
}
}
Upvotes: 3
Views: 9320
Reputation: 1
{template: `<div>{{name}}</div>`}
should be:
{template: `<div>${name}</div>`}
Upvotes: 0
Reputation: 6735
I posted the question into github and got the right answer, please check this for more details.
First approach, check code here
Seconde approach, check code here
ngx-formly
to v5.beta
at this moment I compose this answer.Upvotes: 1
Reputation: 417
Set up the module
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
FormlyModule.forRoot({
types: [
{ name: 'customInput', component: FormlyFieldInput },
]
}),
],
declarations: [ AppComponent, FormlyFieldInput ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Set up custom component and listen to keyup
@Component({
selector: 'formly-field-input',
template: `
<div>{{this.model.profilePictureNotEditable}}</div>
<input type="text" [formControl]="formControl" [formlyAttributes]="field">`,
})
export class FormlyFieldInput extends FieldType implements OnInit {
val;
constructor() {
super();
}
ngOnInit() {
console.log(this.key);
console.log(this.model)
}
}
Set up the form correctly in app.component
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form" (ngSubmit)="submit(model)">
<formly-form [model]="model" [fields]="fields">
<button type="submit">Submit</button>
</formly-form>
</form>
{{ model|json }}
`,
})
export class AppComponent {
form = new FormGroup({});
model = {profilePictureNotEditable: 'John'};
fields: FormlyFieldConfig[] = [
{
fieldGroup: [
{
key: 'name',
type: 'customInput',
templateOptions: {
label: 'Field 1',
type: 'text',
placeholder: 'Formly is terrific!',
},
}]
}];
submit(model) {
console.log(model);
this.model.profilePictureNotEditable = 'this will be the profile picture!'
}
}
https://stackblitz.com/edit/ngx-formly-custom-template-ydrfss Hope this will help you!!
Upvotes: 3