简体   繁体   English

Angular-在不同的父元素中动态添加组件

[英]Angular - Adding components dynamically in different parent elements

I want to build a multi-step form, where each step is its own tab and the user can go forward/backwards through the form. 我想构建一个多步骤表单,其中每个步骤都是自己的标签,用户可以在表单中前进/后退。 Each tab has a header, content and navigation buttons. 每个选项卡都有标题,内容和导航按钮。

In my form component, I have an array of all components (each represents a step in the form) and I want to loop through it in the form's template, so that each step has the same structure and if I want to change that structure I should only change the code in the loop, as it's the same for all steps. 在我的表单组件中,我有一个所有组件的数组(每个组件代表表单中的一个步骤),我想在表单的模板中循环遍历它,以便每个步骤都具有相同的结构,如果我想更改该结构,应该只在循环中更改代码,因为所有步骤都相同。

This is the array in the form.component.ts : 这是form.component.ts中的数组:

steps = [
    LanguageComponent,
    CodeComponent,
    HardwareComponent,
    SubmissionComponent
]

Or should it be: 或者应该是:

steps = [
    new LanguageComponent,
    new CodeComponent,
    new HardwareComponent,
    new SubmissionComponent
]

?

This is the pseudo form.component.html: 这是伪form.component.html:

<div id="tabs">
    <div class="tab" *ngFor="let step of steps" id="{{step.header}}">
        {{ step.header }}
        <app-step></app-step>
        {{ buttons }}
    </div>
</div>

Each step component has header property. 每个步骤组件都有标题属性。

That way, in order to change the structure of the tab, I only have to change it here once, if the header and buttons go inside each components' template, then I will have to change each component's template, if I want to change the tab structure. 这样,为了更改选项卡的结构,我只需要在这里更改一次,如果标题和按钮位于每个组件的模板内,则如果要更改选项卡,则必须更改每个组件的模板。标签结构。

How would you do this, is there a better way to achieve this structure? 您将如何执行此操作,是否有更好的方法来实现此结构?

Thank you! 谢谢!

You need a placeholder component that houses the form tab structure. 您需要一个占位符组件,用于容纳表单选项卡结构。 Then like you said you only have 1 place that you would have to change the layout. 然后就像您说的那样,您只有1个位置需要更改布局。

AppFormTabComponent.html AppFormTabComponent.html

<ngb-tabset>
    <ngb-tab>
        <ngbTemplate>
           <language-component [form]="form"></language-component>
        </ngbTemplate>
    </ngb-tab>
    <ngb-tab>
        <ngbTemplate>
           <code-component [form]="form"></code-component>
        </ngbTemplate>
    </ngb-tab>
    ...
</ngb-tabset>

Then you would only call your AppFormTabComponent once to use it 然后,您只需调用一次AppFormTabComponent即可使用它

form.component.html form.component.html

<app-form-tab-component [form]="form"></app-form-tab-component>

And your form would be in the app.component.ts page and you would pass the form in to each one of your templates. 您的表单将在app.component.ts页面中,并将该表单传递给每个模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM