从组件调用的多个角度4指令实例补充了输入值

xze*_*gga 9 javascript angular-directive angular-components angular

我有一个角度4的组件,被称为三次.在模板元数据中,我有一个带有指令的div,带有一些这样的绑定.

@import {gServ} from '../gServ.service';

@Component: ({
   selector: 'sr-comp',
   template: `<div gDirective [cOptions]="dataChart">`
})

export class SGComponent implements OnInit {
    @Input('report') public report: IReportInstance;
    cOptions:any;

    constructor(private gServ: gServ) {
    }

    ngOnInit(){

        this.cOptions = {};
        this.cOptions = this.gServ.objectMerge(this.gServ.defaultOpt, this.report.opt);

        //this.report.opt is binded to a component when is instantiated.
        //this.gServ.objectMerge is a function that merge the two objects
    }
}
Run Code Online (Sandbox Code Playgroud)

this.cOptions改变了组件的每个实例,然后在指令中我有这个:

import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[gDirective]'
})
export class SGDirective implements OnInit {
  public _element: any;
  @Input() public cOptions: string;

  constructor(public element: ElementRef) {
    this._element = this.element.nativeElement;
  }

  ngOnInit() {
    console.log(this.cOptions);
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是console.log(this.cOptions);始终打印相同的对象,即使组件在组件的方法中设置cOptions了不同的值ngOnInit.

你有什么问题吗?

小智 3

您的组件属性绑定[cOptions]="dataChart"看起来不太好,原因是您dataChart甚至没有定义。它应该就像[DIRECTIVE_PROPERTY]="COMPONENT_PROPERTY"你的COMPONENT_PROPERTY甚至没有在SGComponent组件类中定义。

你的组件类应该是这样的:

@import {gServ} from '../gServ.service';

@Component: ({
   selector: 'sr-comp',
   template: `<div gDirective [cOptions]="Options">`
})

export class SGComponent implements OnInit {
    @Input('report') public report: IReportInstance;
    Options:any;

    constructor(private gServ: gServ) {
    }

    ngOnInit(){
        this.Options = {};
        this.Options = this.gServ.objectMerge(this.gServ.defaultOpt, this.report.opt);
    }
} 
Run Code Online (Sandbox Code Playgroud)