Angular Formio自定义组件

时间:2020-04-08 06:30:37

标签: angular formio

我已经按照Formio文档创建了自定义组件,但是我只是一个初学者,所以我无法使其正常工作。我想创建自定义组件来实现此页面

enter image description here

我想创建自定义组件,例如添加新卡,您可以选择该卡的子代,例如视频或图像,输入等。基本上,我想实现Google Forms Builder,我发现Formio是表单的最佳选择生成器,但我被这个自定义组件卡住了。我听说有人终于在stackoverflow中创建了自定义组件,我也向他们提出了问题。那么,有人可以帮助我吗?也许您有供我参考的源代码,或者什么,非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我已经成功完成了一段时间。

首先,在Formio中找到一个可以完成所需工作的现有组件。如果您的新元素只是呈现非交互的内容,那么您可以使用“ HTML”组件。

这是您需要的代码:

var htmlComponent = Formio.Components.components.htmlelement; // or whatever
class MyNewComponent extends htmlComponent{

  static schema(...extend) {
    return super.schema({
          type: 'MyNewComponent',
          label: "The Default Label",
          any_other_fields: "",
    }, ...extend);

    static get builderInfo() {
      return {
        title: 'Name in the Builder',
        group: 'custom',
        icon: 'picture-o',
        weight: 5,
        schema: this.schema()
      };
    }

    render(element) {
      // Here's where you add your HTML to get put up.
      // 
      tpl += "<div ref='myref'>Hi there!</div>";
      // Note the use of the 'ref' tag, which is used later to find 
      // parts of your rendered element.
      
      // If you need to render the superclass,
      // you can do that with 
      // tpl+=super.render(element);

      // This wraps your template to give it the standard label and bulider decorations         
      return Formio.Components.components.component.prototype.render.call(this,tpl);

    }
    
    attach(element) {
      // This code is called after rendering, when the DOM has been created.
      // You can find your elements above like this:
      this.loadRefs(element, {myref: 'single'});

      var superattach = super.attach(element);
       // Here do whatever you need to attach event handlers to the dom.
      this.refs.myref.on('click',()=>{alert("hi!");});                    

      return superattach;
    }
    
    getvalue() {
      return 3; // the value this element puts into the form
    }
    // OR, depending on which component type you're basing on:
    getValueAt(index,value,flags) {}

    setValue(value) {
      // modify your DOM here to reflect that the value should be 'value'.
    };
    // OR, depending on what component type:
    getValueAt(index) {}

  }
  
  // This sets the form that pops up in the Builder when you create
  // one of these.  It is basically just a standard form, and you
  // can look at the contents of this in the debugger.
  MyNewComponent.editForm = htmlComponent.editForm;


  // Register your component to Formio
  Formio.Components.addComponent('MyNewComponent', MyNewComponent);

这是来之不易的知识;希望对别人有帮助。