簡體   English   中英

Angular 4-使用指令屬性共享數據

[英]Angular 4 - Share data with directive attribute

我正在嘗試制作工具提示指令/組件,但是我嘗試的所有操作都無法在工具提示中使用插值來重復使用變量。 我的家庭標記看起來像這樣:

<md-card class='col-md-3 image-gallery' *ngFor="let advertiser of AdvertiserService.advertisers;let i = index" [@fadeIn]>
    <md-card-content 
    [tooltip]="template" [advertiser]="advertiser">
        //some other markup
    </md-card-content>
</md-card>

我的工具提示指令如下所示:

import { ComponentFactoryResolver, ComponentRef, Directive, ElementRef, 
HostListener, Injector, Output, Input, ReflectiveInjector, Renderer2,     
TemplateRef, Type, ViewContainerRef, ViewRef } from '@angular/core';
import { TooltipComponent } from './tooltip.component';
import { AdvertiserClass } from './../advertiser/advertiser-class';

@Directive({
    selector: '[tooltip]'
})
export class TooltipDirective {
    // We can pass string, template or component
    @Input('tooltip') content: string | TemplateRef<any> | Type<any>;
    @Input('advertiser') advertiser: AdvertiserClass;
    private componentRef: ComponentRef<TooltipComponent>;

    constructor(private element: ElementRef,
        private renderer: Renderer2,
        private injector: Injector,
        private resolver: ComponentFactoryResolver,
        private vcr: ViewContainerRef) {
    }

    @HostListener('mouseenter')
    mouseenter() {
        //console.log(this.advertiser);
        if (this.componentRef) return;
        const factory = 
this.resolver.resolveComponentFactory(TooltipComponent);
        const injector = ReflectiveInjector.resolveAndCreate([
            {
                provide: 'tooltipConfig',
                useValue: {
                    host: this.element.nativeElement
                }
            }
        ]);
        this.componentRef = this.vcr.createComponent(factory, 0, injector, 
this.generateNgContent());
    }

    generateNgContent() {
        if (typeof this.content === 'string') {
            const element = this.renderer.createText(this.content);
            return [[element]];
        }

        if (this.content instanceof TemplateRef) {
            const viewRef = this.content.createEmbeddedView({});
            return [viewRef.rootNodes];
        }

        // Else it's a component
        const factory = this.resolver.resolveComponentFactory(this.content);
        const viewRef = factory.create(this.injector);
        return [[viewRef.location.nativeElement]];
    }

    @HostListener('mouseout')
    mouseout() {
        this.destroy();
    }

    destroy() {
        this.componentRef && this.componentRef.destroy();
        this.componentRef = null;
    }

    ngOnDestroy() {
        this.destroy();
    }
}

我的工具提示組件如下所示:

import { Component, Directive, ElementRef, Inject, OnInit, ViewChild, Input         
} from '@angular/core';
import { AdvertiserClass } from './../advertiser/advertiser-class';

@Directive({
    selector: '.tooltip-container'
})
export class TooltipContainerDirective {
}

@Component({
    template: `
    <div class="tooltip-container" [ngStyle]="{top: top}">
        {{advertiser | json}}
    </div>
  `,
    styles: [
        `
      .tooltip-container {
        background-color: black;
        color: #fff;
        display: inline-block;
        padding: 0.5em;
        position: absolute;
      }
    `
    ]
})
export class TooltipComponent implements OnInit {
    @Input('advertiser') advertiser: AdvertiserClass;
    top: string;
    @ViewChild(TooltipContainerDirective, { read: ElementRef }) private 
tooltipContainer;

    constructor( @Inject('tooltipConfig') private config) {
    }

    ngOnInit() {
        const { top } = this.config.host.getBoundingClientRect();
        const { height } = 
this.tooltipContainer.nativeElement.getBoundingClientRect();
        this.top = `${top - height}px`;
    }
}

如何在可行的代碼中使用{{advertisers}}插補廣告? 我已經嘗試過每種方法,但是我無法將重復的數據傳遞給工具提示組件模板。

照原樣,您的tooltip指令了解廣告商,但使用TooltipComponent(其數據用於生成視圖)卻不知道。 您需要做的是在指令創建廣告商時將廣告商從指令傳遞到TooltipComponent。 我可能會在要創建並注入TooltipComponent的'tooltipconfig'對象中執行此操作。

    const injector = ReflectiveInjector.resolveAndCreate([
        {
            provide: 'tooltipConfig',
            useValue: {
                host: this.element.nativeElement,
                advertiser: this.advertiser
            }
        }
    ]);

然后,在ToolTipComponent中,您可以將該值從構造函數中的config對象中拉出,以使其可用於模板

constructor( @Inject('tooltipConfig') private config) {
    this.advertiser = config.advertiser;
}

或者您可以在構造函數中將配置對象公開,然后綁定到模板中的{{config.advertiser}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM