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

时间:2018-11-18 11:08:34

标签: angular angular-formly

我正在使用ngx-formly,并尝试引入一个自定义模板,该模板仅用于查看。当模板是静态的时,就可以了,但是如果我尝试引入一些角度操作,那是行不通的。参见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);
  }
}

3 个答案:

答案 0 :(得分:1)

设置模块

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

设置自定义组件并听键盘提示

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

答案 1 :(得分:0)

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

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

    • 它不支持可操作
  • 第二种方法,检查代码here

    • 它支持可观察性,但是现在我必须将此答案从ngx-formly升级到v5.beta

答案 2 :(得分:0)

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

应该是:

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

template literals