Angular: Pass Component to a Component

北慕城南 提交于 2019-12-05 04:43:57

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: `
      <div class="widget-wrapper">
         <ng-container *ngFor="let widget of widgets">
             <!-- use a ngSwitchCase here for different types-->
             <grid-test-widget [widget]="widget" *ngIf="widget.active && widget.type === 'test'"></grid-widget>
         </ng-container>          
      </div>
    `,
    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:

<moving-grid> 
  <test-widget class="grid-item-content-001" #widget [active]="false"></test>
  <test-widget class="grid-item-content-002" #widget></test>
</moving-grid>

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: `<div #content>I say hello<li>i</li><li>u</li><button (click)="test()">click me</button> world</div>`
})
export class GridTestWidgetComponent{}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!