0

我有一个使用 Element Ref 和 Renderer 2 来设置元素样式的指令。我想知道如何在此指令中使用渲染器或任何其他方式设置占位符的样式。

代码

TextSizeDirective.ts

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

import { Service } from '../service';

@Directive({
selector: '[textType]'
})

export class TextSizeDirective implements OnInit {

      @Input() textType: string;

      constructor(private el: ElementRef, private s:Service, private renderer: Renderer2) {}

      ngOnInit() {

      this.s.getText().subscribe(data => {

      if (data === 'max' && this.textType === 'title') {

        this.renderer.setStyle(this.el.nativeElement, 'font-size', '25px');

         //How to style placeholder of this element like above?

      }else if (data === 'max' && this.textType === 'text') {

        this.renderer.setStyle(this.el.nativeElement, 'font-size', '16px');
         //How to style placeholder of this element like above?
      } 
    });
  }
}

应用组件.html

<div>
<h1 [textType]="'title'">Heading</h1>
<p [textType]="'text'">Paragraph</p>
<input [textType]="'text'" type="text" placeholder="Placeholder"/>
</div>
4

1 回答 1

0

您可以在要附加 ::placeholder 属性的 CSS 文件中创建一个 css 类,并在指令中使用

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

constructor(private el: ElementRef, private renderer: Renderer2) {
}
ngOnInit() {
   // for my usecase i prefere this
   this.el.nativeElement.classList.add("yourCssClass")
   // or 
   this.renderer.setElementClass(this.elementRef, 'class');
}
于 2021-12-15T14:18:17.267 回答