如何使用ngx-formly实现动态自定义模板

How to achieve dynamic custom template using ngx-formly

我正在使用ngx-formly,并尝试引入一个自定义模板,仅供查看。当模板是静态的时候还可以,但是如果我尝试引入一些angular操作,就不行了。参见 this demo。有什么建议吗?

@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);
  }
}

设置模块

@NgModule({
   imports: [ 
     BrowserModule,
     ReactiveFormsModule,
     FormlyModule.forRoot({
       types: [
        { name: 'customInput', component: FormlyFieldInput },
       ]
     }),
   ],
   declarations: [ AppComponent, FormlyFieldInput ],
   bootstrap:    [ AppComponent ]
})
export class AppModule { }

设置自定义组件并监听 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)
    }

}

在 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 希望对您有所帮助!!

我将问题发布到 github 并得到了正确答案,请查看 this 了解更多详情。

  • 第一种方法,检查代码here

    • 不支持obervable
  • 第二种方法,查看代码here

    • 它支持observable,但是现在必须升级ngx-formlyv5.beta我写这个答案。
{template: `<div>{{name}}</div>`}

应该是:

{template: `<div>${name}</div>`}

template literals