Angular: Pass Component to a Component

后端 未结 1 1146
悲哀的现实
悲哀的现实 2020-12-31 08:43

I have this small gridComponent:

@Component({
    selector: \'moving-grid\',
    templateUrl: \'./grid.component.html\',
    styleUrls: [\'./grid.component.c         


        
1条回答
  •  一个人的身影
    2020-12-31 09:16

    You should not use an @Input to pass in the components. You can use @ContentChildren for that and an abstract WidgetComponent:

    @Component({
        selector: 'moving-grid',
        template: `
          
    `, styleUrls: ['./grid.component.css'] }) export class GridComponent implements AfterContentInit { @ContentChildren('widget') widgets: WidgetComponent[]; ngAfterContentInit() { //your components will be available here } }

    The template of your third component will stay the same, but without the [widgets] and an added #widget name:

     
      
      
    
    

    Your TestWidgetComponent which will extend an abstract WidgetComponent :

    @Directive({
      selector: 'test-widget'
    })
    export class TestWidgetComponent extends WidgetComponent {
        public type: string = 'test';
    }
    

    And your WidgetComponent:

    @Injectable()
    export class WidgetComponent {
    
       @Input()
       public active: boolean;
    
       public type: string;
    
    }
    

    And you'll have several grid widgets based on the type of the widget:

    @Component({
      selector: 'grid-test-widget',
      template: `
    I say hello
  • i
  • u
  • world
    ` }) export class GridTestWidgetComponent{}

    0 讨论(0)
提交回复
热议问题