【发布时间】:2017-09-23 02:04:23
【问题描述】:
我在 Angular 4 中有一个组件,它被调用了 3 次。在模板元数据中,我有一个带有指令的 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
}
}
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);
}
}
问题在于console.log(this.cOptions); 总是打印同一个对象,即使组件在组件的ngOnInit 方法中设置了具有不同值的cOptions。
你知道出了什么问题吗?
【问题讨论】:
-
我有类似的问题。
-
你有没有直接尝试
console.log服务的结果,在你的组件ngOnInit。this.cOptions = this.gServ.objectMerge(...); console.log(this.cOptions);
标签: javascript angular angular-directive angular-components