Tengo la siguiente directiva (TextElementDirective), que tiene 4 variables de entrada colorHex, fontFamily, fontWeight, fontStyle. Quiero establecer el color y el estilo de un elemento usando esta directiva.
@Directive( { selector: "[text-element-map]", // host: { // '(mousemove)': "onMouseMove()" // } } ) export class TextElementDirective{ @Input() colorHex : string; @Input() fontFamily : string; @Input() fontWeight : string; @Input() fontStyle : string; constructor(private el: ElementRef){ this.setElement(); } setElement(){ if(this.colorHex){ this.el.nativeElement.style.color = this.colorHex; } if(this.fontFamily){ this.el.nativeElement.style.fontFamily = this.fontFamily; } if(this.fontWeight){ this.el.nativeElement.style.fontWeight = this.fontWeight; } if(this.fontStyle){ this.el.nativeElement.style.fontStyle = this.fontStyle || ""; } } onMouseMove(){ this.setElement(); } }Cuando uso esta directiva en otro componente, como un atributo, no establece el estilo y el color del elemento. Incluso si hace clic en el botón, los valores de los elementos no se establecen.
Si uso un host (onmousemove) en la directiva, funciona bien. Pero quiero establecer los valores durante el inicio.
¿Alguna idea de lo que me estoy perdiendo?
Aquí está el componente de prueba que lo usa.
@Component({ template: ` <h3>Test</h3> <div> <span>text-element-map: </span> <span class="text-content" text-element-map [colorHex]="colorHex" [fontFamily]="fontFamily" [fontWeight]="fontWeight" [fontStyle]="fontStyle">Change this text</span> <button (click)="setCurrentDesignElement()">Click</button> </div> `, directives:[TextElementDirective], changeDetection: ChangeDetectionStrategy.Default }) export class TestComponent{ @ViewChild(TextElementDirective) private childTextElement: TextElementDirective; colorHex: string = "#e2e2e2"; fontFamily: string = "Arial"; fontWeight: string = "normal"; fontStyle: string = "normal"; setCurrentDesignElement(){ this.color = { hex: "#B4B4B4", id: 5745, name: "Athletic Heather" }; this.font = { cssString: "Valera Round", weight: "normal", style: "italic" }; this.colorHex = "#B4B4B4"; this.fontFamily = "Valera Round"; this.fontWeight = "normal"; this.fontStyle = "italic"; //this.childTextElement.setElement(); } }Input() s no están disponibles en el constructor. Se establecen mediante la detección de cambios y la detección de cambios se ejecuta después de crear una instancia del componente. Los ganchos del ciclo de vida ngOnChanges (cada actualización) y ngOnInit (una vez después de la primera llamada ngOnChanges ) se llaman después de que la detección de cambios actualizó una entrada:
Cambio
constructor(private el: ElementRef){ this.setElement(); }para
constructor(private el: ElementRef) {}; ngOnInit() { this.setElement(); } Se ngOnInit() después de inicializar las entradas.
En vez de
this.el.nativeElement.style.color = this.colorHex;es mejor usar
@HostBinding('style.color') @Input() colorHex : string; @HostBinding('style.font-family') @Input() fontFamily : string; @HostBinding('style.font-weight') @Input() fontWeight : string; @HostBinding('style.font-style') @Input() fontStyle : string; En realidad, no he intentado agregar @HostBinding() y @Input() en el mismo campo, pero no veo por qué no funcionaría.