I have a component in angular 4 that is called three times. In template metadata I have a div with a directive with some bindings like this.
@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 change for every instance of the component, then in the directive I have this:
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);
}
}
The problem is that console.log(this.cOptions);
always print the same object, even when component set cOptions
with diferent values in ngOnInit
method of the compnent.
Do you have some idea what is wrong?
As with components, you can add multiple directive property bindings to a host element.
Q 16 - Which of the following is true about ng-model directive? A - ng-model directive binds the values of AngularJS application data to HTML input controls.
You can't use id or selectors that span multiple elements. With , separated multiple selectors can be used where the component is added to elements where one of these matches.
What is meant by directives in Angular? Directives are classes that add new behavior or modify the existing behavior to the elements in the template. Basically directives are used to manipulate the DOM, for example adding/removing the element from DOM or changing the appearance of the DOM elements.
Your component property binding [cOptions]="dataChart"
doesn't look good, reason being your dataChart
is not even defined. it should be like [DIRECTIVE_PROPERTY]="COMPONENT_PROPERTY"
and your COMPONENT_PROPERTY
is not even defined in SGComponent
component class.
Your component class should be something like this:
@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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With