有没有办法通过继承重用表单组件?

时间:2018-03-15 10:45:10

标签: angular forms typescript

亲爱的Stackoverflow用户,

我没有看到关于这个问题的任何例子,但我应该首先提到我的计划。

我有三个不同的页面,基本上共享许多FormGroups。他们的差异基本上是微不足道的,也许是一两个FormControls。当然,我基本上可以复制粘贴整个组件,只是添加我需要的控件,但我觉得这是一个相当不切实际和混乱的解决方案。我该如何正确处理这个问题?一般来说,Angular中有关继承的任何好资源吗?官方页面似乎没有提到我在英雄课程中看到的内容。

2 个答案:

答案 0 :(得分:1)

我不知道为什么我认为它并不像我想象的那么简单。 首先,我创建一个FormBuilder类,它设置我使用的所有其他表单之间共享的所有控件。现在,任何扩展FormBuilder类的组件都能够创建这样的表单。

this.queryForm.addControl('newControl', new FormControl(''))

因此,只需添加

即可轻松包含我需要的FormControl
library(gapminder)
gapminder

by_country <- gapminder %>% 
  group_by(country, continent) %>% 
  nest()

country_model <- function(df) {
  lm(lifeExp ~ year, data = df)
}

by_country <- by_country %>% 
  mutate(model = map(data, country_model))

by_country %>% 
  mutate(model_lag = lag(model))

# A tibble: 142 x 5
   country     continent data              model    model_lag
   <fct>       <fct>     <list>            <list>   <list>   
 1 Afghanistan Asia      <tibble [12 x 4]> <S3: lm> <lgl [1]>
 2 Albania     Europe    <tibble [12 x 4]> <S3: lm> <S3: lm> 
 3 Algeria     Africa    <tibble [12 x 4]> <S3: lm> <S3: lm> 
 4 Angola      Africa    <tibble [12 x 4]> <S3: lm> <S3: lm> 
 5 Argentina   Americas  <tibble [12 x 4]> <S3: lm> <S3: lm> 
 6 Australia   Oceania   <tibble [12 x 4]> <S3: lm> <S3: lm> 
 7 Austria     Europe    <tibble [12 x 4]> <S3: lm> <S3: lm> 
 8 Bahrain     Asia      <tibble [12 x 4]> <S3: lm> <S3: lm> 
 9 Bangladesh  Asia      <tibble [12 x 4]> <S3: lm> <S3: lm> 
10 Belgium     Europe    <tibble [12 x 4]> <S3: lm> <S3: lm> 
# ... with 132 more rows

因此组件的html代码几乎不需要任何更改。

答案 1 :(得分:0)

您可以使用内容投影来完成此操作。

假设您有一个带有两个输入的FormGroup组件。该组件也将具有ng-content,以便其他组件可以注入自己的html。

@Component({
    selector: 'my-form-group',
    template: `
        Type something : <input type="text"/> 
        Select something: <select> ... </select>
        Insert your own stuff: <ng-content></ng-content>
    `
})
export class FormGroupComponent {}

@Component({
    selector: 'my-form-group-radio',
    template: `
        <my-form-group>
             <input type="radio" name="myOption" value="1" />
             <input type="radio" name="myOption" value="2" />
        </my-form-group>
    `
})
export class FromGroupRadioComponent {}

通过这种方式,您可以根据需要多次重复使用FormGroupComponent。您可以创建不同类型的组件并投影不同的内容。