【问题标题】:Angular2, how to include component dependent on valueAngular2,如何包含依赖于值的组件
【发布时间】:2016-04-29 06:47:21
【问题描述】:

我有以下 HTML 代码:

<pm-application [node]="node" *ngIf="node.type ==='application'"></pm-application>
<pm-proxy [node]="node" *ngIf="node.type ==='proxy'"></pm-proxy>
<pm-part [node]="node" *ngIf="node.type ==='part'"></pm-part>
<pm-certificate [node]="node" *ngIf="node.type ==='certificate'"></pm-certificate>
<pm-portal [node]="node" *ngIf="node.type ==='portal'"></pm-portal>

它看起来不太好,还有很多其他类型,所以列表会增加。有没有更简单的方法?比如:

<{{node.type}} [node]="node"><{{node.type}}>

【问题讨论】:

    标签: angular angular2-template angular2-directives


    【解决方案1】:

    你可以使用类似的组件

    beta.17

    @Component({
      selector: 'dcl-wrapper',
      template: '', //`<div #target></div>`
    })
    export class DclWrapper {
      // alternative way of getting a `ViewContainerRef` for an element inside the view instead of the host itself
      //@ViewChild('target', {read: ViewContainerRef}) target;
    
      constructor(private dcl:DynamicComponentLoader, private target:ViewContainerRef) {}
      @Input() type;
    
      ngOnChanges() {
        if(this.cmpRef) {
          throw 'currently changing type after the component was added is not supported'
        }
        this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
          this.cmpRef = cmpRef;
        });
      }
    }
    

    Plunker beta.17

    !!

    @Component({
      selector: 'dcl-wrapper',
      template: `<div #target></div>`
    })
    export class DclWrapper {
      constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
      @Input() type;
    
      ngOnChanges() {
        if(this.cmpRef) {
          this.cmpRef.dispose();
        }
        this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
          this.cmpRef = cmpRef;
        });
      }
    }
    

    (来自Angular 2 dynamic tabs with user-click chosen components

    然后在你的组件中使用它

    @Component({  
      directives: [DclWrapper],
      template: `
      <dcl-wrapper [type]="types[node.type]"></dcl-wrapper>
    `})
    export class ParentComponent {
      types = {
        application: PmApplicationComponent,
        proxy: PmProxyComponent,
        part: PmPartComponent,
        certificate: PmCertificateComponent,
        portal: PmPortalComponent,
      };
    }
    

    您不能对添加的组件使用 [node]="node" 之类的绑定 DynamicComponentLoader 但您可以将数据传递给 DclWrapper 并将数据强制传递给包装的组件。如果您觉得这种方法很有趣,我可以详细说明一下。

    【讨论】:

    【解决方案2】:

    我不确定这在 Angular 2 中是否可行,但在 v1 中,您可以在指令中使用限制属性来使用 css 类或属性而不是节点名称。

    如果这不可能,我会创建一个超级组件

    <pm-supercomponent [node]="node"/>
    

    并在此组件内设置开关。那么至少你不需要一直重复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 2017-04-21
      • 2015-01-17
      • 2020-07-05
      • 2022-09-28
      • 1970-01-01
      • 2010-09-19
      相关资源
      最近更新 更多